天天看點

全排列Ⅱ-leetcoe - 47

給定一個可包含重複數字的序列,傳回所有不重複的全排列。

示例:  輸入: [1,1,2] 輸出: [ [1,1,2], [1,2,1], [2,1,1] ]

思路:用set集合去重

public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> res = new ArrayList<>();
    dsf(nums, res, 0);
    return res;
}
public static void dfs(int[] nums, List<List<Integer>> res, int start){
    if(start == nums.length){
        List<Integer> list = new ArrayList<>();
        for(int num : nums){
            list.add(num);
        }
        res.add(list);
    }
    Set<Integer> set = new HashSet<>();
    for(int i = start; i < nums.lenght; i++){
        if(set.add(nums[i])){
            swap(nums, i, start);
            dfs(nums, res, start + 1);
            swap(nums, i, start);
        }
    }
}
public static void swap(int[] nums, int i, int j){
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}