给定一个可包含重复数字的序列,返回所有不重复的全排列。
示例:
输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> L = new ArrayList<>();
perm2(nums, 0, L);
return L;
}
public static void perm2(int[] nums, int start, List<List<Integer>> L) {
if (start == nums.length) {
List<Integer> list = new ArrayList<>();
for (int n : nums) {
list.add(n);
}
boolean f = true;
if (L.size() != 0) {
for (int i = 0; i < L.size(); ++i) {
if(L.get(i).equals(list)) {
f = false;
break;
}
}
}
if (f) {
L.add(list);
}
return;
}
for (int i = start; i < nums.length; i++) {
swap(nums, start, i);
perm2(nums, start + 1, L);
swap(nums, i, start);
}
}
public static void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
}
网友评论