【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)
相关推荐
To_OC7 小时前
LC 128 最长连续序列:别上来就排序,O (n) 解法才是这题的灵魂
javascript·算法·leetcode
05Kevin20 小时前
lk每日冒险题--数据结构6.27
算法
To_OC1 天前
从一次栈溢出报错说起,我把递归彻底扒明白了
javascript·算法·程序员
千纸鹤安安1 天前
千问Qwen-AgentWorld来了:一个语言模型搞定七大Agent场景,GPT-5.4都输了
算法
七牛开发者2 天前
MCP 到底是什么?为什么 Agent 都想接上它
算法·aigc·agent
kisshyshy2 天前
从递归到迭代,一文吃透二叉树的核心知识与 JavaScript 实现
javascript·算法·代码规范
To_OC2 天前
LC 49 字母异位词分组:想到哈希表很简单,选对 key 才是精髓
javascript·算法·leetcode