Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
分析:
这和Permutations的方法是一样的,不同的地方就是加了一个判断,判断当前元素是否已经当过头元素,即从start开始到curr如果有
和curr相等的元素,说明curr已经当过头元素,不能再交换了。
public class Solution {
public List<List<Integer>> permuteUnique(int[] num) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if(num==null || num.length==0)
return res;
dfs(res, num, 0);
return res;
}
private void dfs(List<List<Integer>> res, int[] num, int start){
if(start == num.length){
res.add(arrayToList(num));
return;
}
for(int i=start; i<num.length; i++){
//不同之处就是这里加了一个判断
if(isValid(num, start, i)){
swap(num, start, i);
dfs(res, num, start+1);
swap(num, start, i);
}
}
}
private List<Integer> arrayToList(int[] num){
List<Integer> list = new ArrayList<Integer>();
for(int i=0; i<num.length; i++)
list.add(num[i]);
return list;
}
private boolean isValid(int[] num, int start, int curr){
//如果curr之前有和curr一样的元素,说明curr已经背移动到前面过了
for(int i=start; i<curr; i++){
if(num[i] == num[curr])
return false;
}
return true;
}
private void swap(int[] num, int index1, int index2){
int temp = num[index1];
num[index1] = num[index2];
num[index2] = temp;
}
}