一开始使用DFS,加使用集合来去重,结果TLE。
改进,参考别人的代码:
1. 先对nums数组做一个排序;
2. 在dfs的时候,判断一下
if (k > 0 && nums[k] == nums[k-1] && flags[k-1]==false)
continue;
原因如下:假设有如下序列[x, x, x, a1, a2, x, x, x], 这里是X代表任意数,a1=a2
这段代码是要保证a1排在a2前面,就能够避免重复
List<List<Integer>> permutations = new ArrayList<List<Integer>>();
public void dfs(int i, int[] nums, boolean[] flags, LinkedList<Integer> permutation){
if (i == nums.length){
permutations.add(new LinkedList<>(permutation));
}else{
for (int k = 0; k < nums.length; k ++){
if (flags[k] == false){
if (k > 0 && nums[k] == nums[k-1] && flags[k-1]==false)
continue;
flags[k] = true;
permutation.addLast(nums[k]);
dfs(i+1, nums, flags, permutation);
flags[k] = false;
permutation.removeLast();
}
}
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
boolean[] flags = new boolean[nums.length];
LinkedList<Integer> permutation = new LinkedList<Integer>();
dfs(0, nums, flags, permutation);
return this.permutations;
}