【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)
相关推荐
小黑屋的黑小子1 分钟前
【数据结构】HashMap源码 —— 简单介绍
数据结构·算法·面试·源码·hashmap
林泽毅35 分钟前
UNet脑瘤医学影像分割训练实战(PyTorch 完整代码)
深度学习·算法·机器学习
珊瑚里的鱼1 小时前
【双指针】专题:LeetCode 202题解——快乐数
开发语言·c++·笔记·算法·leetcode·职场和发展
David Bates1 小时前
代码随想录第18天:二叉树
python·算法·二叉树
想成为配环境大佬1 小时前
P8739 [蓝桥杯 2020 国 C] 重复字符串
算法·蓝桥杯·贪心
莫有杯子的龙潭峡谷2 小时前
4.15 代码随想录第四十四天打卡
c++·算法
A懿轩A2 小时前
2025年十六届蓝桥杯Python B组原题及代码解析
python·算法·蓝桥杯·idle·b组
灋✘逞_兇2 小时前
快速幂+公共父节点
数据结构·c++·算法·leetcode
姜行运3 小时前
每日算法(双指针算法)(Day 1)
c++·算法·c#
stoneSkySpace3 小时前
算法——BFS
前端·javascript·算法