问题原始链接 https://leetcode.com/problems/permutations-ii
给定一个数集,集合中的数可能重复。返回所有排列,结果中不能有重复排列。
例如,[1,1,2] 有以下不重复排列:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
public class Solution {
public static List<List<Integer>> permuteUnique(int[] nums) {
if (nums == null || nums.length == 0) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> result = new ArrayList<List<Integer>>();
p(nums, 0, result);
return result;
}
private static void p(int[] a, int i, List<List<Integer>> result) {
if (i == a.length - 1) {
result.add(toList(a));
return;
}
p(a, i + 1, result);
for (int j = i + 1; j < a.length; j++) {
if (!contains(a, i, j, a[j])) {
swap(a, i, j);
p(a, i + 1, result);
swap(a, i, j);
}
}
}
private static boolean contains(int[] a, int start, int end, int x) {
for (int i = start; i < end; i++) {
if (a[i] == x) {
return true;
}
}
return false;
}
private static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static List<Integer> toList(int[] a) {
List<Integer> result = new ArrayList<Integer>(a.length);
for (Integer i : a) {
result.add(i);
}
return result;
}
}