Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2] Output: [ [1,1,2], [1,2,1], [2,1,1] ]
重新实现next_permutation()
/**
*
* @author dongb
* Permutations
* rebuild next_purmation()
* TC O(n!), SC O(1)
*/
public class Solution {
public static List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(nums);
do {
ArrayList<Integer> first = new ArrayList<>();
for (int i: nums) {
first.add(i);
}
result.add(first);
} while (nextPermutation(nums, 0, nums.length));
return result;
}
private static boolean nextPermutation(int[] nums, int begin, int end) {
// From right to left, find the first digit(partitionNumber)
// which violates the increase trend
int p = end - 2;
while (p > -1 && nums[p] >= nums[p + 1]) --p;
// If not found, which means current sequence is already the largest
// permutation, then rearrange to the first permutation and return false
if(p == -1) {
reverse(nums, begin, end);
return false;
}
// From right to left, find the first digit which is greater
// than the partition number, call it changeNumber
int c = end - 1;
while (c > 0 && nums[c] <= nums[p]) --c;
// Swap the partitionNumber and changeNumber
swap(nums, p, c);
// Reverse all the digits on the right of partitionNumber
reverse(nums, p+1, end);
return true;
}
private static void swap(int[] nums, int i, int j) {
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
private static void reverse(int[] nums, int begin, int end) {
end--;
while (begin < end) {
swap(nums, begin++, end--);
}
}
}
递归
递归函数 permute() 的参数 p ,是中间结果,它的长度又能标记当前走到了哪一步,用于判断收敛条件。扩展节点,每次从小到大,选一个没有被用光的元素,直到所有元素被用光。 本题不需要判重,因为状态装换图是一颗有层次的树
/**
*
* @author dongb
* Permutations
* Recursion, DSF, incremental construction, boolean selected
* TC O(n!), SC O(n)
*/
public class Solution {
public static List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> result = new ArrayList<>(); // final result
List<Integer> path = new ArrayList<>(); // intermediate result
boolean[] selected = new boolean[nums.length];
permute(nums, selected, path, result);
return result;
}
static void permute(int[] nums, boolean[] selected,
List<Integer> path, List<List<Integer>> result) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (selected[i]) {
continue;
}
if (i > 0 && nums[i - 1] == nums[i] && !selected[i - 1]) {
continue;
}
selected[i] = true;
path.add(nums[i]);
permute(nums, selected, path, result);
selected[i] = false;
path.remove(path.size() - 1);
}
}
}