刷刷刷 Day 28 | 78. 子集
78. 子集
LeetCode题目要求
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例
输入:nums = [1,2,3] 输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
解题思路
子集需要的是所有可能性,所以要取所有节点
上代码
class Solution { private List<List<Integer>> res = new ArrayList<>(); private Deque<Integer> path = new LinkedList<>(); public List<List<Integer>> subsets(int[] nums) { backtracking(nums, 0); return res; } private void backtracking(int[] nums, int startIndex) { res.add(new ArrayList<>(path)); // 终止条件 if (startIndex >= nums.length) { return; } // 单层循环 for (int i = startIndex; i < nums.length; i++) { path.add(nums[i]); backtracking(nums, i + 1); path.removeLast(); } } }
附:学习资料链接
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了