Problem Description:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
Code:
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Set<List<Integer>> tes = new HashSet<List<Integer>>();
public List<List<Integer>> permuteUnique(int[] nums) {
List<Integer> tmp = new ArrayList<Integer>();
boolean[] flag = new boolean[nums.length + 1];
for(int i = 0; i < nums.length; i++) {
flag[i] = true;
tmp.add(nums[i]);
func(flag, i, nums, tmp);
flag[i] = false;
tmp.remove(0);
}
return res;
}
void func(boolean[] flag, int cur, int[] nums, List<Integer> tmp) {
if(tmp.size() == nums.length) {
if(!tes.contains(tmp)) {
List<Integer> out = new ArrayList<Integer>();
out.addAll(tmp);
res.add(out);
}
tes.add(tmp);
return;
}
for(int i = 0; i < nums.length; i++) {
if(!flag[i]) {
flag[i] = true;
tmp.add(nums[i]);
func(flag, i, nums, tmp);
flag[i] = false;
tmp.remove(tmp.size() - 1);
}
}
}
}