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,那个总结帖里有提到过
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
Arrays.sort(nums);
helper(ans, new ArrayList(), nums, new boolean[nums.length]);
return ans;
}
private void helper(List<List<Integer>> ans, List<Integer> list, int[] nums, boolean[] visited){
if(list.size()==visited.length) ans.add(new ArrayList(list));
for(int i=0; i<visited.length; i++){
if(visited[i] || (i>0 && nums[i]==nums[i-1] && !visited[i-1])) continue;
visited[i] = true;
list.add(nums[i]);
helper(ans, list, nums, visited);
visited[i] = false;
list.remove(list.size()-1);
}
}
}