【leetcode hot 100 78】子集

解法一:回溯法

java 复制代码
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        backtrace(0, nums, result, temp);
        return result;
    }

    public void backtrace(int i, int[] nums, List result, List temp){
        result.add(new ArrayList<Integer>(temp)); // 加入元素个数为i的子集 这里类型强转要用new

        for(int j=i; j<nums.length; j++){
            // j=i表示j之前的元素遍历过了,要遍历j后面的元素
            temp.add(nums[j]);
            backtrace(j+1, nums, result, temp);  
            temp.remove(temp.size()-1);
        }
        // 1 2 3 的输出方式为[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
    }
}

注意:

  • 这里类型转换要用new:result.add(new ArrayList<Integer>(temp)),而不是强转ArrayList<Integer>(temp)
相关推荐
residual_fan29 分钟前
持续对比强化学习(Continual Contrastive Reinforcement Learning)论文分享
人工智能·算法·数据挖掘·数据分析
s_w.h1 小时前
【 计网 】序列化与反序列化
linux·服务器·网络·算法·bash
信奥卷王1 小时前
2025年09月GESPC++五级真题解析(含视频)
算法
白狐_7981 小时前
408 数据结构|外部排序:流程与 k 路归并
数据结构·算法
闻缺陷则喜何志丹1 小时前
【动态规划】P3609 [USACO17JAN] Hoof, Paper, Scissor G
c++·算法·动态规划·洛谷
leihefeng2 小时前
手写数字识别:KNN vs 逻辑回归实战
python·算法·机器学习·逻辑回归·scikit-learn
全栈技术负责人2 小时前
DeepSeek Harness 业务工具权限插件 dsh-tool-permission设计思路
网络·算法·ai·ai编程
mmmmath_32 小时前
面试题 02.07. 链表相交
算法·链表
圣保罗的大教堂3 小时前
leetcode 3903. 最小稳定下标 I 简单
leetcode
residual_fan3 小时前
特征级SMOTE(Feature-level SMOTE)论文分享
人工智能·算法·数据挖掘·数据分析