回溯算法之子集问题 leetxode子集问题78,90,491

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();
        }
    }
}
  • 13
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值