给定一个可包含重复数字的序列,返回所有不重复的全排列。
    示例:
    输入: [1,1,2]
    输出:
    [
    [1,1,2],
    [1,2,1],
    [2,1,1]
    ]
    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/permutations-ii


    思路:
    上一题是没有重复的数字,这题数字允许重复
    总的思路和上一题一样,增加一个条件判断,判断当前形成的路径和上一条路径是不是相同的

    1. class Solution {
    2. public List<List<Integer>> permuteUnique(int[] nums) {
    3. //特殊情况判断
    4. List<List<Integer>> res = new LinkedList();
    5. if (nums == null || nums.length == 0){
    6. return res;
    7. }
    8. boolean [] isVisited = new boolean[nums.length];
    9. Deque<Integer> path = new ArrayDeque<Integer>();
    10. dfs(nums,0,path,res,isVisited);
    11. return res;
    12. }
    13. private void dfs(int[] nums, int depth, Deque<Integer> path, List<List<Integer>> res, boolean[] isVisited) {
    14. if (depth == nums.length){
    15. res.add(new ArrayList<>(path));
    16. return;
    17. }
    18. for (int i = 0; i < nums.length; i++) {
    19. if (i != 0 && nums[i] == nums[i - 1] && !isVisited[i - 1]) {
    20. continue; // 防止重复
    21. }
    22. if (isVisited[i]){
    23. continue;
    24. }
    25. isVisited[i] = true;
    26. path.add(nums[i]);
    27. dfs(nums,depth + 1,path,res,isVisited);
    28. path.remove(nums[i]);
    29. isVisited[i] = false;
    30. }
    31. }
    32. }