【LeetCode刷题】-- 78.子集

78.子集

java 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        dfs(0,nums,ans,list);
        return ans;
    }
    private void dfs(int cur,int[] nums,List<List<Integer>> ans,List<Integer> list){
        //每更新一次List,都加入结果,首先加进来的是空集
        ans.add(new ArrayList<>(list));
        for(int i = cur;i<nums.length;i++){
            //将当前数加入List
            list.add(nums[i]);
            //递归,不能重复使用当前树,下一轮从i+1开始
            dfs(i+1,nums,ans,list);
            //回溯,回退刚刚加到的数
            list.remove(list.size()-1);
        } 
    }
}
相关推荐
欧叶冲冲冲4 分钟前
Python常见数据结构的CRUD(LeetCode高频版速查)
数据结构·python·leetcode
祖力5522 分钟前
Linux应用软件编程:目录IO与framebuffer
linux·运维·算法·framebuffer·目录io
名字还没想好☜28 分钟前
Go 用 slices/maps 标准库泛型函数:告别手写 Contains、Sort、去重(Go 1.21)
开发语言·后端·算法·golang·go
地平线开发者29 分钟前
【模型轻量化专题】深度学习模型为什么需要轻量化
算法
圣保罗的大教堂31 分钟前
leetcode 3622. 判断整除性 简单
leetcode
_Narcissus_1 小时前
链表算法题和静态链表
数据结构·c++·笔记·算法·链表·ai·力扣
Lyyaoo.1 小时前
【普通数组】【中等】除了自身以外数组的乘积
数据结构·算法·leetcode
threerocks1 小时前
《The AI-Native SDLC Playbook》万字拆解
算法·aigc·ai编程
夏玉林的学习之路2 小时前
算法8.环形队列
算法
O。O蛋黄酥啊2 小时前
GraphRAG 和 LightRAG 详解与对比
人工智能·python·算法·rag·graphrag·lightrag