Problem 4 Permutation II with duplication
Method 1: Swap- Swap(只对permutation有效)
public List<List<Integer>> permutation(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
backTracking(result, nums, 0);
return result;
}
// level: index: 当前层我正要固定index
// [0, index - 1]已经固定好的元素,不能用
// [index, nums.length - 1] 可以用来被固定到当前位置的元素
private void backTracking(List<List<Integer>> result, int[] nums, int level) {
if (level == nums.length) {
List<Integer> current = new ArrayList<>();
for (int num: nums) {
current.add(num);
}
result.add(current);
return;
}
// 纵向上自动避免重复(swap - swap)
// 横向上需要我们自己去重
Set<Integer> valueHasBeenFixedInThisLevel = new HashSet<>();
for (int i = level; i < nums.length; i++) {
if (!valueHasBeenFixedInThisLevel.contains(nums[i])) {
valueHasBeenFixedInThisLevel.add(nums[i]);
swap(nums, i, level);
backTracking(result, nums, level + 1);
swap(nums, i, level);
}
//valueHasBeenFixedInThisLevel.remove(nums[i]); //不能吐,这是同一层,不需要吃吐
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}Method 2 一个个加,怎么把横纵都去重
Last updated