Link to original problem: 这里写链接内容
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], and [2,1,1].
Related Problem:
46 Permutations: 这里写链接内容
本题需要考虑的比46 Permutations略微复杂了一些,因为这里的输入不再是1到n了,而是一个任意给定的整数数组,需要我们考虑避免重复的问题。
跳过重复的idea比较简单,即先排序,使用排序好的数组。如果遇到某个元素,其值跟上一个数字相同,但是上一个数字并未放入背包,那么这个数字也不能放入背包,需要跳过。
下面是具体代码:
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(nums == null || nums.length == 0) return res;
Arrays.sort(nums);
List<Integer> cur = new ArrayList<Integer>();
boolean[] used = new boolean[nums.length];
helper(res, cur, nums, used, 0);
return res;
}
private void helper(List<List<Integer>> res, List<Integer> cur, int[] nums, boolean[] used, int count){
if(count == nums.length){
res.add(new ArrayList<Integer>(cur));
return;
}
for(int ii = 0; ii < nums.length; ii++){
if(used[ii] == false){
if(ii > 0 && (nums[ii] == nums[ii-1] && used[ii-1] == false)) continue;
cur.add(nums[ii]);
used[ii] = true;
helper(res, cur, nums, used, count+1);
cur.remove(cur.size()-1);
used[ii] = false;
}
}
}
}
1112

被折叠的 条评论
为什么被折叠?



