Permutations II

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

答案
Permutation II 只需要在Permutation的基础上,确保同一个位置i上如果已经选择了数字num, 则不能再次选择(use a set for this)

class Solution {
    public List> permuteUnique(int[] nums) {
        List> list = new ArrayList>();
        List curr = new ArrayList();
        boolean[] used = new boolean[nums.length];
        recur(nums, used, 0, curr, list);
        return list;
    }
    
    private void recur(int[] nums, boolean[] used, int i, List curr, List> list) {
        if(i == nums.length) {
            list.add(new ArrayList(curr));
            return;
        }

        Set set = new HashSet();
        for(int j = 0; j < nums.length; j++) {
            if(set.contains(nums[j])) continue;
            if(!used[j]) {
                set.add(nums[j]);
                curr.add(nums[j]);
                used[j] = true;
                recur(nums, used, i + 1, curr, list);
                used[j] = false;
                curr.remove(curr.size() - 1);                
            }
        }
    }
}

你可能感兴趣的:(Permutations II)