【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 天前
算法6:相交链表
数据结构·算法·链表
nglff1 天前
蓝桥杯抱佛脚第二天|简单枚举,前缀和
算法·职场和发展·蓝桥杯
2301_793804691 天前
C++安全编程指南
开发语言·c++·算法
m0_518019481 天前
分布式系统安全通信
开发语言·c++·算法
AC__dream1 天前
2024秋招-字节跳动-算法岗笔试
数据结构·算法
一叶落4381 天前
LeetCode 151. 反转字符串中的单词(C语言)【双指针 + 字符串处理】
c语言·数据结构·算法·leetcode
_olone1 天前
牛客每日一题:刷题统计(Java)
java·算法·容斥原理·牛客
无敌憨憨大王1 天前
DFS(深搜)
算法·深度优先·图论
junnhwan1 天前
LeetCode Hot 100——栈
java·数据结构·算法·leetcode·hot 100
sqyno1sky1 天前
代码动态生成技术
开发语言·c++·算法