本题求自增子序列,是不能对原数组进行排序的,排完序的数组都是自增子序列了。
所以不能使用之前的去重逻辑!
在图中可以看出,同一父节点下的同层上使用过的元素就不能再使用了
可以使用数组 或者 map 去重
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return res;
}
private void backtracking(int[] nums, int startIndex){
if(path.size() > 1){
res.add(new ArrayList<>(path)); // 注意这里不要加return,要取树上的节点
}
Map<Integer, Integer> map = new HashMap<>();
for(int i = startIndex; i < nums.length; i++){
if(!path.isEmpty() && nums[i] < path.get(path.size() - 1)){
continue;
}
if(map.getOrDefault(nums[i], 0) >= 1){
continue;
}
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
path.add(nums[i]);
backtracking(nums, i+1);
path.remove(path.size() - 1);
}
}
}
注意:
1.由于递归树的每一个节点都要记录结果 所以res.add() 之后不return
2.这里每层递归新建一个map 用来对每一树层进行去重
第一次做排列问题
排列是有序的,也就是说 [1,2] 和 [2,1] 是两个集合,这和之前分析的子集以及组合所不同的地方
可以看出元素1在[1,2]中已经使用过了,但是在[2,1]中还要在使用一次1,所以处理排列问题就不用使用startIndex了。
但排列问题需要一个used数组,标记已经选择的元素,如图橘黄色部分所示:
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
backtracking(nums);
return res;
}
private void backtracking(int[] nums){
if(path.size() == nums.length){
res.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(!used[i]){
used[i] = true;
path.add(nums[i]);
backtracking(nums);
used[i] = false;
path.remove(path.size() - 1);
}
}
}
}
也可以使用ArrayList 中的 contains方法
通过判断path中是否存在数字,排除已经选择的数字
public void backtrack(int[] nums, LinkedList<Integer> path) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
}
for (int i =0; i < nums.length; i++) {
// 如果path中已有,则跳过
if (path.contains(nums[i])) {
continue;
}
path.add(nums[i]);
backtrack(nums, path);
path.removeLast();
}
}
排列问题的不同:
- 每层都是从0开始搜索而不是startIndex
- 需要used数组记录path里都放了哪些元素了
又涉及去重的逻辑
还要强调的是去重一定要对元素进行排序,这样我们才方便通过相邻的节点来判断是否重复使用了。
组合问题和排列问题是在树形结构的叶子节点上收集结果,而子集问题就是取树上所有节点的结果。
这题还是同一树层不能重复取 但是 同一树枝可以重复取
class Solution {
List<List<Integer>> res = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean[nums.length];
Arrays.sort(nums);
Arrays.fill(used, false);
backtracking(nums);
return res;
}
private void backtracking(int[] nums){
if(path.size() == nums.length){
res.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(i > 0 && nums[i] == nums[i-1] && used[i-1] == false){
continue;
}
if(!used[i]){
used[i] = true;
path.add(nums[i]);
backtracking(nums);
path.remove(path.size() - 1);
used[i] = false;
}
}
}
}
关键是这一步
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
// used[i - 1] == true,说明同一树枝nums[i - 1]使用过
// used[i - 1] == false,说明同一树层nums[i - 1]使用过
// 如果同一树层nums[i - 1]使用过则直接跳过
continue;
}