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], [2,1,1] ]
Difficulty: Medium
Solution: Back-Tracking
import java.util.Hashtable;
public class Solution {
public void helper(List<List<Integer>> res, int[] nums, Hashtable<Integer, Integer> ht, List<Integer> curr){
for(int i = 0; i < nums.length; i++){
if(ht.get(i) == 1){
if(i > 0 && nums[i] == nums[i-1] && ht.get(i-1) == 1)
continue;
ht.put(i, 0);
curr.add(nums[i]);
if(curr.size() == nums.length){
res.add(new ArrayList(curr));
curr.remove(curr.size() - 1);
ht.put(i, 1);
}
else{
helper(res, nums, ht, curr);
curr.remove(curr.size() - 1);
ht.put(i, 1);
}
}
}
return;
}
public List<List<Integer>> permuteUnique(int[] nums) {
Hashtable<Integer, Integer> ht = new Hashtable<Integer, Integer>();
Arrays.sort(nums);
for(int i = 0; i < nums.length; i++){
ht.put(i, 1);
}
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> temp = new ArrayList<Integer>();
helper(res, nums, ht, temp);
return res;
}
}