Shawngbk / Leecode

Questions of Leecode
0 stars 0 forks source link

47. Permutations II #154

Open Shawngbk opened 7 years ago

Shawngbk commented 7 years ago

public class Solution { public List<List> permuteUnique(int[] nums) { List<List> res = new ArrayList<List>(); Set<List> set = new HashSet<List>(); helper(nums, res, set, 0); return res; }

private void helper(int[] nums, List<List<Integer>> res, Set<List<Integer>> set, int index) {
    if(index == nums.length) {
        List<Integer> list = new ArrayList<Integer>();
        for(int i : nums)
        list.add(i);
        if(!set.contains(list)) {
            set.add(list);
            res.add(list);
        }
    }
    for(int i = index; i < nums.length; i++) {
        swap(nums, index, i);
        helper(nums, res, set, index+1);
        //使得数组的顺序可以恢复成交换前的顺序,能够满足所有的情况
        swap(nums, i, index);
    }
}

private void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

}

Shawngbk commented 7 years ago

LinkedIn Microsoft