47. Permutations II

来源:互联网 发布:无锡移动网络办理 编辑:程序博客网 时间:2024/06/08 11:23

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

For example,
[1,1,2] have the following unique permutations:

[  [1,1,2],  [1,2,1],  [2,1,1]]
求排列组合,去掉重复的。程序如下:

class Solution {    public void swap(int[] nums, int i, int j){        int tmp = nums[i];        nums[i] = nums[j];        nums[j] = tmp;    }    public void traceBacking(int[] nums, List<List<Integer>> llst, int start){        if (start == nums.length){            List<Integer> lst = new ArrayList<>();            for (int val : nums){                lst.add(val);            }            llst.add(lst);            return;        }        for (int i = start; i < nums.length; ++ i){            if (i != start&&(nums[start] == nums[i]||nums[i-1] == nums[i])){                continue;            }            swap(nums, start, i);            traceBacking(nums, llst, start + 1);           // swap(nums, start, i);        }        for (int i = start; i < nums.length - 1; ++ i){            swap(nums, i+1, i);        }    }        public List<List<Integer>> permuteUnique(int[] nums) {        List<List<Integer>> result = new ArrayList<>();        Arrays.sort(nums);        traceBacking(nums, result, 0);        return result;    }}



原创粉丝点击