leetcode78. 子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

cpp 复制代码
示例 1:

输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

输入:nums = [0]
输出:[[],[0]]

先上代码:

cpp 复制代码
class Solution {
    public void dfs(List<List<Integer>> res, List<Integer>cnt, int st, int len, int[] nums) {
        if(len == cnt.size()) res.add(new ArrayList<Integer>(cnt));
        //System.out.println(len+"  "+ cnt.size());
        for(int i = st; i < nums.length; i++) {
            cnt.add(nums[i]);
            dfs(res, cnt, i+1, len+1, nums);
            cnt.remove(cnt.size() - 1);
        }
    }
    public List<List<Integer>> subsets(int[] nums) {

        List<List<Integer>>res = new ArrayList<>();
        List<Integer>cnt = new ArrayList<>();
        //for(int i = 0; i < nums.length; i++) cnt.add(nums[i]);
        dfs(res, cnt, 0, 0,nums);
        return res;
    }

首先要滤清回溯的思路,

每次做判断选或者不选,然后恢复状态

相关推荐
ゞ 正在缓冲99%…5 分钟前
leetcode918.环形子数组的最大和
数据结构·算法·leetcode·动态规划
Kaltistss1 小时前
98.验证二叉搜索树
算法·leetcode·职场和发展
知己如祭1 小时前
图论基础(DFS、BFS、拓扑排序)
算法
mit6.8241 小时前
[Cyclone] 哈希算法 | SIMD优化哈希计算 | 大数运算 (Int类)
算法·哈希算法
c++bug1 小时前
动态规划VS记忆化搜索(2)
算法·动态规划
哪 吒1 小时前
2025B卷 - 华为OD机试七日集训第5期 - 按算法分类,由易到难,循序渐进,玩转OD(Python/JS/C/C++)
python·算法·华为od·华为od机试·2025b卷
军训猫猫头2 小时前
1.如何对多个控件进行高效的绑定 C#例子 WPF例子
开发语言·算法·c#·.net
success2 小时前
【爆刷力扣-数组】二分查找 及 衍生题型
算法
Orlando cron3 小时前
数据结构入门:链表
数据结构·算法·链表
牛客企业服务4 小时前
2025年AI面试推荐榜单,数字化招聘转型优选
人工智能·python·算法·面试·职场和发展·金融·求职招聘