题目:
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] ]
思路:
用计数器记录每个数字出现的次数,然后dfs深度优先搜索,每搜一次,该数字计数器减一,最后回溯
class Solution {int [] input;int len;int [] result;List <List<Integer>> output;Map<Integer, Integer> map;Set<Integer> set;int keylen;void dfs(int depth){if(depth==len){List<Integer> AddToOutput=new ArrayList<Integer>();for(int k=0;k<len;k++){AddToOutput.add(result[k]);}output.add(AddToOutput);return;}for(int i=0;i<keylen;i++){int value=map.get(input[i]);if(value>=1){result[depth]=input[i];map.put(input[i], value-1);dfs(depth+1);map.put(input[i], value);}}}public List<List<Integer>> permuteUnique(int[] nums) {len=nums.length;map=new HashMap<Integer, Integer>();for(int i=0;i<len;i++){if(map.get(nums[i])==null){map.put(nums[i], 1);}else{int tmp=map.get(nums[i]);map.put(nums[i],tmp+1);}}set=map.keySet();keylen=set.size();input=new int[keylen];Iterator<Integer>it=set.iterator();int cnt=0;while(it.hasNext()){input[cnt++]=it.next();}result=new int[len];output=new ArrayList<>();dfs(0);return output;}
}