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] ]
思路:与Permutations类似,这回是有重复元素,所以对于1,2,1来说1,2,1与1,2,1中1作为第一次递归入口的结果是重复的,为了避免重复,不能让两个1都为递归入口,所以先排序,变成1,1,2,当第一个1已经作为过本次递归的入口时,下个1就不能作为本次递归的入口。由于有重复元素,所以不能像之前那样用arraylist.contains判断是否使用过,而是用一个额外的数组存储使用信息。
public class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> list = new ArrayList<List<Integer>>();
boolean[] used = new boolean[nums.length];
List<Integer> l = new ArrayList<Integer>();
dfs(list, l, nums, used);
return list;
}
public void dfs(List<List<Integer>> List, List<Integer> l, int[] nums, boolean[] used) {
if (l.size() == nums.length) {
List.add(new ArrayList<Integer>(l));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] || i > 0 && nums[i-1]==nums[i] && used[i - 1] == false)
continue;
used[i] = true;
l.add(nums[i]);
dfs(List, l, nums, used);
used[i] = false;
l.remove(l.size() - 1);
}
}
}