😁47 permutation II

https://leetcode.com/problems/permutations-ii/

仍然用swap的方法做,但是要去重,idea是在这个地方固定过的数不能再次被固定,所以用个set来记录哪些数字被换到index处过就可以了

class Solution {
    private List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        dfs(nums, 0);
        return ans;
    }
    private void dfs(int[] nums, int index){
        if (index == nums.length) {
            List<Integer> array = new ArrayList<>();
            for (int i = 0; i < index; i++) {
                array.add(nums[i]);
            }
            ans.add(array);
            return;
        }
        Set<Integer> fixed = new HashSet<>();
        for (int i = index; i < nums.length; i++) {
            if (fixed.contains(nums[i])) continue;
            fixed.add(nums[i]);
            swap(nums, i, index);
            dfs(nums, index + 1);
            swap(nums, i, index);
        }
    }
    private void swap(int[] nums, int i, int j) {
        int tmp = nums[i];
        nums[i] = nums[j];
        nums[j] = tmp;
    }
}

Last updated