78. 子集

回溯问题系列
leetcode链接

又是一个回溯问题。

  • 递归参数:当前遍历数组索引,当前的路径
  • 返回条件:索引为数组末尾
  • 递归工作:加入或者不加入索引指向的元素到当前路径
  • 返回参数:无

算法复杂度

  • O ( n ∗ 2 n ) O(n*2^n) O(n2n) 2 n 2^n 2n n n n为数组长度,因为得到一条路径需要 O ( n ) O(n) O(n)的时间
  • O ( n ) O(n) O(n),递归深度为 n n n
class Solution {
	// 用于返回结果
    List<List<Integer>> res = new LinkedList();
    int[] nums;
    

    public List<List<Integer>> subsets(int[] nums) {
        this.nums = nums;
        subsets(0, new LinkedList<Integer>());
        return res;
    }

    private void subsets(int i, LinkedList<Integer> curPath){
        // 访问到最后一个节点,加入路径
        if(i == nums.length){
            // 不能这么写res.add(curPath);
            // 要新建一个对象
            res.add(new LinkedList(curPath));
            return;
        }
		// 进行回溯,加入和不加入这条路径
        curPath.add(nums[i]);
        subsets(i + 1, curPath);
        curPath.removeLast();
        subsets(i + 1, curPath);
    }
}

当然,也可以这么写

class Solution {

    List<List<Integer>> res = new LinkedList();
    int[] nums;
    

    public List<List<Integer>> subsets(int[] nums) {
        this.nums = nums;
        subsets(0, new LinkedList<Integer>());
        // 访问数组默认为false;
        return res;
    }

    private void subsets(int start, LinkedList<Integer> curPath){
    	// 加入当前路径
        res.add(new LinkedList(curPath));
        // 遍历每个元素,每个元素先加入路径递归,然后再移除
        for(int i = start; i < nums.length; i++){
            curPath.add(nums[i]);
            subsets(i + 1, curPath);
            curPath.removeLast();
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值