题目链接: * 491.递增子序列
看完代码随想录之后的想法:
我们在进行树层去重的时候,我们对于每一次for循环,我们需要新建一个set,记录每一层出现过的数,如果出现过的话,后面就不能再使用了;
class Solution {
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
void backTracking(int[] nums, int startIndex) {
if(path.size() > 1)
result.add(new LinkedList<>(path));
HashSet<Integer> set = new HashSet<>();
for(int i = startIndex; i < nums.length; i++) {
if(!path.isEmpty() && nums[i] < path.peekLast() || set.contains(nums[i]))
continue;
set.add(nums[i]);
path.add(nums[i]);
backTracking(nums, i + 1);
path.pollLast();
}
}
public List<List<Integer>> findSubsequences(int[] nums) {
backTracking(nums, 0);
return result;
}
}
题目链接: * 46.全排列
文章讲解:代码随想录
视频讲解:组合与排列的区别,回溯算法求解的时候,有何不同?| LeetCode:46.全排列_哔哩哔哩_bilibili
看完代码随想录之后的想法:
我们需要注意,我们回溯三部曲
终止条件 path.size() == nums.length;
for,我们要注意,在递归的时候我们需要跳过的是已经使用过的数,然而该数前和后面的数依旧可以使用;我们需要使用used数组来标记我们之前使用过的数;
class Solution {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> result = new LinkedList<>();
void backTracking(int[] nums, int[] used) {
if(path.size() == nums.length) {
result.add(new LinkedList(path));
return ;
}
for(int i = 0; i < nums.length; i++) {
if(used[i] == 1)
continue;
used[i] = 1;
path.add(nums[i]);
backTracking(nums, used);
used[i] = 0;
path.pollLast();
}
}
public List<List<Integer>> permute(int[] nums) {
int[] used = new int[nums.length];
backTracking(nums, used);
return result;
}
}
题目链接: 47.全排列 II
看完代码随想录之后的想法:
首先使用全排列的基本方法,不过我们需要进行去重,那么我们首先需要对数组进行排序;
然后使用这个代码
f(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0)
continue;
class Solution {
List<List<Integer>> result = new LinkedList<>();
LinkedList<Integer> path = new LinkedList<>();
void backTracking(int[] nums, int[] used) {
if(path.size() == nums.length) {
result.add(new LinkedList<>(path));
return ;
}
for(int i = 0; i < nums.length; i++) {
if(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == 0)
continue;
if(used[i] == 1) continue;
used[i] = 1;
path.add(nums[i]);
backTracking(nums, used);
used[i] = 0;
path.pollLast();
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
int[] used = new int[nums.length];
backTracking(nums, used);
return result;
}
}