78. Subsets
Given a set of distinct integers, nums, return all possible subsets.
Note: The solution set must not contain duplicate subsets.
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
含义:给一个没有重复数字的字符串,获取所有的子串(子串中不能有重复数字)
方法一:BFS
1 public List<List<Integer>> subsets(int[] nums) { 2 // The idea is: 3 // 起始subset集为:[] 4 // 添加S0后为:[], [S0] 5 // 添加S1后为:[], [S0], [S1], [S0, S1] 6 // 添加S2后为:[], [S0], [S1], [S0, S1], [S2], [S0, S2], [S1, S2], [S0, S1, S2] 7 // 红色subset为每次新增的。显然规律为添加Si后,新增的subset为克隆现有的所有subset,并在它们后面都加上Si。 8 9 List<List<Integer>> result = new ArrayList<List<Integer>>(); 10 List<Integer> tmp = new ArrayList<Integer>(); 11 result.add(tmp); // add empty set 12 Arrays.sort(nums); 13 for (int i=0;i<nums.length;i++) 14 { 15 int n = result.size(); 16 for (int j=0;j<n;j++) 17 { 18 tmp = new ArrayList<Integer>(result.get(j)); 19 tmp.add(nums[i]); 20 result.add(new ArrayList<Integer>(tmp)); 21 } 22 } 23 return result; 24 }
方法二:回溯算法|递归实现
本解法采用回溯算法实现,回溯算法的基本形式是“递归+循环”,正因为循环中嵌套着递归,递归中包含循环,这才使得回溯比一般的递归和单纯的循环更难理解,其实我们熟悉了它的基本形式,就会觉得这样的算法难度也不是很大。原数组中的每个元素有两种状态:存在和不存在。
① 外层循环逐一往中间集合 temp 中加入元素 nums[i],使这个元素处于存在状态
② 开始递归,递归中携带加入新元素的 temp,并且下一次循环的起始是 i 元素的下一个,因而递归中更新 i 值为 i + 1
③ 将这个从中间集合 temp 中移除,使该元素处于不存在状态
1 public class Solution { 2 public List<List<Integer>> subsets(int[] nums) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 List<Integer> temp = new ArrayList<Integer>(); 5 dfs(res, temp, nums, 0); 6 return res; 7 } 8 private void dfs(List<List<Integer>> res, List<Integer> temp, int[] nums, int j) { 9 res.add(new ArrayList<Integer>(temp)); 10 for(int i = j; i < nums.length; i++) { 11 temp.add(nums[i]); //① 加入 nums[i] 12 dfs(res, temp, nums, i + 1); //② 递归 13 temp.remove(temp.size() - 1); //③ 移除 nums[i] 14 } 15 } 16 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!