【刷题1】LeetCode 78. 子集 java题解

题目

https://leetcode-cn.com/problems/subsets/
在这里插入图片描述
更新:

class Solution {
    ArrayList<List<Integer>> res=new ArrayList<>();
    int[] nums;
    public List<List<Integer>> subsets(int[] nums) {
        this.nums=nums;
        dfs(new ArrayList<Integer>(),0);// 暂时子集,选取开始位置
        return res;
    }
    public void dfs(ArrayList<Integer> tmp,int start){
        res.add(new ArrayList<>(tmp));//不管当前多长,都加入结果,由于下标的限制不会超过数组长度
        for(int i=start;i<nums.length;i++){
                tmp.add(nums[i]);
                dfs(tmp,i+1);
                tmp.remove(tmp.size()-1);
        }
    }
}

分析

算是官方题解的思路了:
遍历每一位数字,分为取和不取两种情况。

代码

class Solution {
    ArrayList<List<Integer>> res;
    ArrayList<Integer> list;
    int[] nums;
    public List<List<Integer>> subsets(int[] nums) {
        this.nums=nums;
        res=new ArrayList<>();
        if(nums==null||nums.length==0)
            return new ArrayList<>();
        list=new ArrayList<>();
        dfs(0);
        return res;
    }
    public void dfs(int x){
        if(x==nums.length){//遍历完了,从[0,len-1]都经历了取和不取
            res.add(new ArrayList<>(list));
            return;
        }
        //取这个元素
        list.add(nums[x]);
        dfs(x+1);
        list.remove(list.size()-1);
        //不取这个元素
        dfs(x+1);
    }
}

复杂度

在这里插入图片描述

结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值