Open huimeich opened 8 years ago
Recursive
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new LinkedList<List<Integer>> ();
List<Integer> soFar = new LinkedList<Integer>();
Arrays.sort(nums);
for (int i : nums) soFar.add(i);
res = permuteUniqueHelper(res, 0, soFar);
return res;
}
private List<List<Integer>> permuteUniqueHelper(List<List<Integer>> res, int start, List<Integer> soFar) {
if (start == soFar.size() - 1) {
res.add(new LinkedList<Integer>(soFar));
return res;
}
for (int i = start; i < soFar.size(); i++) {
if (i != start && soFar.get(start) == soFar.get(i)) continue;
Collections.swap(soFar,i,start);
res = permuteUniqueHelper(res, start + 1, new LinkedList<Integer>(soFar));
}
return res;
}
}
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].