Problem: Permutation II
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2] Output: [[1,1,2], [1,2,1], [2,1,1]] Example 2:
Input: nums = [1,2,3] Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
Constraints:
1 <= nums.length <= 8 -10 <= nums[i] <= 10
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
HashMap<Integer,Boolean> visited = new HashMap<>();
for(int i = 0; i < nums.length; i++){
visited.put(i,false);
}
List<Integer> list = new ArrayList<>();
List<List<Integer>> ans = new ArrayList();
helper(nums,visited,0,nums.length,list,ans);
return ans;
}
private void helper(int[] nums,HashMap<Integer,Boolean> map,int i, int n, List<Integer> list,List<List<Integer>> ans){
if(i == n){
ans.add(new ArrayList<>(list));
return;
}
HashSet<Integer> set = new HashSet();
for(int j = 0; j < n; j++){
if(map.get(j) == false){
if(set.contains(nums[j]))continue;
list.add(nums[j]);
map.put(j,true);
set.add(nums[j]);
helper(nums, map, i+1, n, list,ans);
list.remove(list.size()-1);
map.put(j,false);
}
}
}
}