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])))

 

47. Permutations II 全排列可重复版本
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

 

 
上一篇:[10.14 workshop] 微服务治理全链路金丝雀发布


下一篇:HTML修改弹出框