码迷,mamicode.com
首页 > 其他好文 > 详细

[Leetcode] Subsets

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

标签:des   style   blog   io   color   ar   os   sp   for   

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

标签:des   style   blog   io   color   ar   os   sp   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!