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]
.
public class Solution {
public void permuteUnique(int[] num, ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tem) {
if(num.length == 0) {
ArrayList<Integer> clone = new ArrayList<Integer>(tem);
res.add(clone);
return;
}
ArrayList<Integer> cache = new ArrayList<Integer>();
for(int i=0; i<num.length; i++) {
if(!cache.contains(num[i])) {
cache.add(num[i]);
int[] nextNum = new int[num.length-1];
int nextLen = 0;
for(int j=0; j<num.length; j++) {
if(j!=i) nextNum[nextLen++] = num[j];
}
tem.add(num[i]);
permuteUnique(nextNum, res, tem);
tem.remove(tem.size()-1);
}
}
return;
}
public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> tem = new ArrayList<Integer>();
permuteUnique(num, res, tem);
return res;
}
}