47. Permutations II 全排列可重复版本

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

有i - 1的时候,要求i > 0,起码等于1
(i > 0) && ((!used[i - 1]) && (nums[i] == nums[i - 1])))

 

class Solution {
    public List<List<Integer>> permuteUnique(int[] nums) {
        //cc
        List<List<Integer>> results = new ArrayList<List<Integer>>();
        boolean[] used = new boolean[nums.length];
        
        if (nums == null || nums.length == 0)
            return results;
        
        //排序一下
        Arrays.sort(nums);
        
        dfs(nums, new ArrayList<Integer>(), used, results);
        
        return results;
    }
    
    public void dfs(int[] nums, List<Integer> temp, boolean[] used, 
                   List<List<Integer>> results) {
        //exit
        if (temp.size() == nums.length)
            results.add(new ArrayList<>(temp));
        
        for (int i = 0; i < nums.length; i++) {
            if ((used[i]) || ((i > 0) && ((!used[i - 1]) && (nums[i] == nums[i - 1]))))
                continue;
            
            temp.add(nums[i]);
            used[i] = true;
            dfs(nums, temp, used, results);
            used[i] = false;
            temp.remove(temp.size() - 1);
        }
 
    }
}
View Code

 

 
posted @ 2020-08-11 07:50  苗妙苗  阅读(96)  评论(0编辑  收藏  举报