78.子集
思路和组合、分割都像,却别是非叶子节点也要加入结果集
难点是突然发现回溯算法一直没有好好想时间复杂度的问题。
class Solution {
List<List<Integer>> res=new ArrayList<>();
LinkedList<Integer> path=new LinkedList<>();
int[] nums;
public List<List<Integer>> subsets(int[] nums) {
this.nums=nums;
res.add(new ArrayList<>());
traceback(0);
return res;
}
public void traceback(int start){
if(start>=nums.length){
return;
}
for(int i=start;i<nums.length;i++){
path.add(nums[i]);
res.add(new LinkedList<>(path));
traceback(i+1);
path.removeLast();
}
}
}
90.子集Ⅱ
去重思路和分割、三数之和都一样。秒了这题
class Solution {
List<List<Integer>> res=new ArrayList<>();
LinkedList<Integer> path=new LinkedList<>();
int[] nums;
public List<List<Integer>> subsetsWithDup(int[] nums) {
res.add(new ArrayList<>());
Arrays.sort(nums);
this.nums=nums;
traceback(0);
return res;
}
public void traceback(int start){
if(start>=nums.length)return;
for(int i=start;i<nums.length;i++){
if(i>start && nums[i]==nums[i-1])continue;
path.add(nums[i]);
res.add(new LinkedList<>(path));
traceback(i+1);
path.removeLast();
}
}
}
491.递增子序列
思路:这个题有了很大的不同 主要不同体现在以下两点
(1)加入结果集的条件,时机仍然是在非叶子节点,条件必须正序——好解决
(2)去重不能在使用之前的方法,因为不能对原数组排序——难解决!!!
重点:去重方法很容易想到哈希树,关键怎么用!
如图,不是一层或者所有节点,而是同一个节点下的同层子节点不能重复选一个数。
同一个节点下的同层子节点就应该是一个traceback里面的节点!
所以是在traceback函数的开头新建hashset,将每次遍历的点加入。
class Solution {
List<List<Integer>> res=new ArrayList<>();
LinkedList<Integer> path=new LinkedList<>();
int[] nums;
public List<List<Integer>> findSubsequences(int[] nums) {
this.nums=nums;
traceback(0,0);
return res;
}
public void traceback(int start,int n){
if(start>nums.length)return;
HashSet<Integer> record=new HashSet<>();
for(int i=start;i<nums.length;i++){
if(record.contains(nums[i]))continue;
record.add(nums[i]);
if(path.size()>0&&nums[i]<path.getLast())continue;
path.add(nums[i]);
if(path.size()>=2){
res.add(new LinkedList<>(path));
}
traceback(i+1,n+1);
path.removeLast();
}
}
}