首页 > 其他 > 详细

[Leetcode] Subsets

时间:2014-11-13 09:19:16      阅读:208      评论:0      收藏:0      [点我收藏+]

Given a set of distinct integers, S, 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 S = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

 

Solution:

 1 public class Subsets {
 2     public List<List<Integer>> subsets(int[] S) {
 3         List<List<Integer>> ret = new ArrayList<List<Integer>>();
 4         List<Integer> path = new ArrayList<Integer>();
 5         
 6         Arrays.sort(S);
 7         
 8         subsets(S, path, ret, 0);
 9         
10         return ret;
11     }
12     
13     public void subsets(int[] S, List<Integer> path, List<List<Integer>> ret, int index) {
14         // 把当前的结果可以添加到结果集中. 空集也算是一种集合 
15         ret.add(new ArrayList<Integer>(path));
16         
17         for (int i = index; i < S.length; i++) {
18             path.add(S[i]);
19             
20             // 注意!这里的index要填写i + 1,而不是index,开始老是会犯错。
21             subsets(S, path, ret, i + 1);
22             path.remove(path.size() - 1);
23         }
24     }
25 }

 

[Leetcode] Subsets

原文:http://www.cnblogs.com/Phoebe815/p/4094055.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!