力扣78 子集 java实现

78.子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

复制代码
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]

示例 2:

复制代码
输入:nums = [0]
输出:[[],[0]]

提示:

  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • nums 中的所有元素 互不相同

递归遍历的时候,把所有节点都记录下来,就是要求的子集集合。

java 复制代码
    public static void main(String[] args) {  // 测试用
       int[] nums = {1,2,3};
       List<List<Integer>> res = subsets(nums);
        for (List<Integer> list : res) {
            System.out.println(list);
        }
    }

    public static  List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        res.add(new ArrayList<>());
        helper(nums, 0, res, new ArrayList<>());

        return res;
    }

    public static void helper(int[] nums, int cur, List<List<Integer>> res, List<Integer> temp){
        if (cur >= nums.length){
            return;
        }
        for (int i = cur; i < nums.length; i++) {
            temp.add(nums[i]);
            res.add(new ArrayList<>(temp));
            helper(nums, i + 1, res, temp);
            temp.remove(temp.size() - 1);
        }
    }

以上为记录分享用,代码较差请见谅

相关推荐
疯狂的喵18 小时前
C++编译期多态实现
开发语言·c++·算法
scx2013100418 小时前
20260129LCA总结
算法·深度优先·图论
2301_7657031418 小时前
C++中的协程编程
开发语言·c++·算法
m0_7487080518 小时前
实时数据压缩库
开发语言·c++·算法
小魏每天都学习18 小时前
【算法——c/c++]
c语言·c++·算法
智码未来学堂19 小时前
探秘 C 语言算法之枚举:解锁解题新思路
c语言·数据结构·算法
惊讶的猫19 小时前
探究StringBuilder和StringBuffer的线程安全问题
java·开发语言
jmxwzy19 小时前
Spring全家桶
java·spring·rpc
Halo_tjn19 小时前
基于封装的专项 知识点
java·前端·python·算法
春日见19 小时前
如何避免代码冲突,拉取分支
linux·人工智能·算法·机器学习·自动驾驶