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]
] 和一般的Permutation不一样的是,这种permutation需要排序,使相同的元素能够相邻,选取下一个元素的时候,要查看这个元素的前一个元素是否和它相同,如果相同而且没有使用过,就不用选取这个元素,因为如果选取了这个元素,所得的结果被包含于选取了前一个相同元素的结果中。
代码如下:
public class Solution {
int length;
public List<List<Integer>> permuteUnique(int[] nums) {
length = nums.length;
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (length == 0) {
return result;
}
Arrays.sort(nums);
boolean[] flags = new boolean[length];
Arrays.fill(flags, false);
List<Integer> candidate = new ArrayList<Integer>();
helper(nums, length, flags, result, candidate);
return result;
}
private void helper(int[] nums, int n, boolean[] flags, List<List<Integer>> result, List<Integer> candidate) {
if (n == 0) {
result.add(new ArrayList<Integer>(candidate));
}
int ll = candidate.size();
for (int i = 0; i < length; i++) {
if (!flags[i]) {
//if the number appears more than once and the same number before it has not been used
if (i != 0 && nums[i] == nums[i - 1] && !flags[i - 1]) {
continue;
}
flags[i] = true;
candidate.add(nums[i]);
helper(nums, n - 1, flags, result, candidate);
candidate.remove(ll);
flags[i] = false;
}
}
}
}