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] ]
方法一:递归
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
backtrack(result, new ArrayList<Integer>(), nums, new boolean[nums.length]);
return result;
}
private static void backtrack(List<List<Integer>> result, ArrayList<Integer> tempList, int[]
nums, boolean[] used) {
if (tempList.size() == nums.length) {
result.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
/**only insert duplicate element
when the previous duplicate element has been inserted*/
if (used[i] || i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
used[i] = true;
tempList.add(nums[i]);
backtrack(result, tempList, nums, used);
used[i] = false;
tempList.remove(tempList.size() - 1);
}
}
}
方法二:
public List<List<Integer>> permuteUnique3(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
result.add(new ArrayList<Integer>());
for (int i = 0; i < nums.length; i++) {
List<List<Integer>> newres = new ArrayList<>();
for (List<Integer> k : result) {
for (int j = 0; j <= k.size(); j++) {
if (j>0 && k.get(j-1) == nums[i]) break;//注意这里的判断和break
List<Integer> list = new ArrayList<>(k);
list.add(j, nums[i]);
newres.add(list);
}
}
result = newres;
}
return result;
}