Subsets
2015-06-17 15:06
246 查看
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 =
a solution is:
这个题目和上一篇的combinations思路非常接近,相当于那里的k从0到n罢了。注意要将给的数组排个序才能用之前的那种方法。
代码如下:
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], [] ]
这个题目和上一篇的combinations思路非常接近,相当于那里的k从0到n罢了。注意要将给的数组排个序才能用之前的那种方法。
代码如下:
public class Solution { int[] S = {}; int len = 0; List<List<Integer>> ans = new ArrayList<List<Integer>>(); //定义为成员变量,方便在不同的函数之间都能使用,不用当做参数,传来传去的。 public List<List<Integer>> subsets(int[] nums) { this.S = nums; this.len = nums.length; Arrays.sort(S); for (int i = 0; i <= len; i++) { dfs(new ArrayList<Integer>(), 0, i); } return ans; } public void dfs(List<Integer> list, int from, int tar) { if (list.size() == tar) { List<Integer> res = new ArrayList<Integer>(list); ans.add(res); } else { for (int i = from; i < len; i++) { list.add(S[i]); backTracking(list, i + 1, tar); list.remove(list.size()-1); } } } }
相关文章推荐
- 计划工作和组织工作
- 各大云服务供应商对初创公司的扶持政策对比
- CodeIgniter实现从网站抓取图片并自动下载到文件夹里的方法
- 本机php环境搭建教程:windows环境下wampserver的配置教程——超级详细
- 万能适配器
- Codeforces551B:ZgukistringZ
- open函数--------------详解,flags参数全面
- TRIANGLE_FAN 有破面的问题
- 视频合并的问题
- 读《一个程序员的生命周期》有感
- javascript运算符优先级
- 阅读<构建之法>第10、11、12章
- BASIC HTTP AUTHENTICATION ON ANDROID
- 严重: IOException while loading persisted sessions: java.io.EOFException
- Eclipse Java注释模板设置详解
- 玩转git和github
- annot refer to a non-final variable * inside an inner class defined in a different method"错误解析
- datagridview自动填充列头
- 发现一个很好的mac和android手机文件互传的工具
- PreparementStatement接口