思路:此题只是在原来的基础上加上可包含重复数字的条件,如果还是通过之前回溯法来解决会有很多重复的数据,因此可以在全排列搜索交换前先判断一下是否已经交换过
回溯的思路可以参考: LeetCode-46.全排列 I
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<Integer> list = new ArrayList<Integer>();
for (int num:nums){
list.add(num);
}
List<List<Integer>> output = new ArrayList<List<Integer>>();
backstack(nums.length,list,output,0);
return output;
}
public void backstack(int num,List<Integer> list,List<List<Integer>> output,int first){
//只需在这里添加判断是否添加进去的序列已存在即可
if (first==num){
output.add(new ArrayList<Integer>(list));
return ;
}
for (int i=first;i<num;i++){
if(canSwap(list,first,i)){
//先判断交换的两个数是否相同
Collections.swap(list,i,first);
//交换后进行回溯
backstack(num,list,output,first+1);
//再换回来
Collections.swap(list,first,i);
}
}
}
private boolean canSwap(List<Integer> list,int begin,int end){
for(int i=begin;i<end;i++){
if(list.get(i)==list.get(end)){
return false;
}
}
return true;
}
}