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] ]
用的是dfs来完成
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums==null||nums.length==0) return null;
Arrays.sort(nums); //把重复数字放在一起
int len = nums.length;
int[] isUsed = new int[len];
List<List<Integer>> result = new ArrayList<List<Integer>>();
ArrrayList<Integer> store = new ArrayList<Integer>();
dfs(result,isUsed,store,nums);
return result;
}
public void dfs(List<List<Integer>> result, int[] isUsed, List<Integer> store, int[] nums) {
if(store.size()==nums.length){
result.add(new ArrayList<Integer>(store));
return;
}
for(int i=0;i<nums.length;i++){
if(isUsed[i]==1)
continue;
if(i>0&&nums[i]==nums[i-1]&&isUsed[i-1]==0) continue; //重复的当前面使用过才可以使用,前面未使用过直接使用会导致解重复
store.add(nums[i]);
isUsed[i]=1;
dfs(result,isUsed,store,nums);
isUsed[i]=0;
store.remove(store.size()-1);
}
}
}
result.add(new ArrayList<Integer>(store));
这个有问题等待补充!