Total Accepted: 8649 Total Submissions: 35072
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 ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
dfs(num, list, 0);
return list;
}
// swap each element into num[index]
public void dfs(int[] num, ArrayList<ArrayList<Integer>> list, int index) {
if(index == num.length) {
ArrayList<Integer> path = new ArrayList<Integer>();
for (int i = 0; i < num.length; i++) path.add(num[i]);
list.add(path);
return;
}
for (int i = index; i < num.length; i++) {
boolean isDup = false;
for (int k = index; k < i ; k++ ) {
if (num[k] == num[i]) isDup = true;
}
if (!isDup){
swap(num, index, i);
dfs(num, list, index + 1);
swap(num, index, i);
}
}
}
public void swap(int[] num, int a, int b) {
int tmp = num[a];
num[a] = num[b];
num[b] = tmp;
}
}