LeetCode Subsets(求所有的集合)
2015-06-06 14:11
316 查看
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If nums =
Given a set of distinct integers, nums, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
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], [] ]
题意:给出一个集合,集合中的元素不相等,求其所有的集合
思路:用DFS,先求出一个元素的集合,然后在生成的集合上再生成新的集合,如[1,2],先生成[],[2],然后再考虑1情况下,生成的新集合有[1],[1,2]
注意,在处理前,数据要先排序
代码如下
public class Solution { private List<List<Integer>> dfs(int cur, int n, int[] nums) { if (cur == n) { List<List<Integer>> ans = new LinkedList<List<Integer>>(); List<Integer> ar = new LinkedList<Integer>(); ans.add(ar); ar = new LinkedList<Integer>(); ar.add(nums ); ans.add(ar); return ans; } List<List<Integer>> ans = new ArrayList<List<Integer>>(); List<List<Integer>> tmp = dfs(cur + 1, n, nums); for (int j = 0; j < tmp.size(); j++) { ans.add(tmp.get(j)); } for (int j = 0; j < tmp.size(); j++) { List<Integer> node = new LinkedList<Integer>(); node.addAll(tmp.get(j)); node.add(0, nums[cur]); ans.add(node); } return ans; } public List<List<Integer>> subsets(int[] nums) { int n = nums.length; Arrays.sort(nums); return dfs(0, n - 1, nums); } }
相关文章推荐
- 转:链接器link.exe 编译器cl.exe 资源编译器rc.exe
- Qt版的Rtsp客户端
- ubuntu 下 Eclipse中syso 快捷键 Alt + / 不能使用的问题
- Linux系统下查看某文件修改的时间戳
- 手把手教popupWindow从下往上,以达到流行效果
- 合并石子
- dict
- LeetCode2 AddTowNumbers
- 【构造】UVa 11387 The 3-Regular Graph
- JsRender实用入门教程
- poj 2540 Hotter Colder(极角计算半平面交)
- docker rmi all
- 【NOIP提高组2005】谁拿了最多奖学金
- ef6 使用 mysql
- Gradle project sync failed. Please fix your project and try
- win8.1安装出错解决方法之一
- 秒表功能实现
- CMake的使用
- Cygwin+vim+cscope+ctags+taglist打造个性IDE开发环境
- centOS7关闭防火墙的命令