【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)
相关推荐
菜鸟懒懒44 分钟前
exp1_code
算法
Winn~1 小时前
JVM垃圾回收器-ZGC
java·jvm·算法
爱coding的橙子1 小时前
每日算法刷题Day24 6.6:leetcode二分答案2道题,用时1h(下次计时20min没写出来直接看题解,节省时间)
java·算法·leetcode
慢慢慢时光1 小时前
leetcode sql50题
算法·leetcode·职场和发展
pay顿1 小时前
力扣LeetBook数组和字符串--二维数组
算法·leetcode
精神小伙mqpm1 小时前
leetcode78. 子集
算法·深度优先
岁忧1 小时前
(nice!!!)(LeetCode每日一题)2434. 使用机器人打印字典序最小的字符串(贪心+栈)
java·c++·算法·leetcode·职场和发展·go
Tisfy1 小时前
LeetCode 2434.使用机器人打印字典序最小的字符串:贪心(栈)——清晰题解
leetcode·机器人·字符串·题解·贪心·
dying_man1 小时前
LeetCode--18.四数之和
算法·leetcode
知识漫步2 小时前
代码随想录算法训练营第60期第五十九天打卡
算法