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

LeetCode-78 Subsets

时间:2015-02-18 00:59:31      阅读:172      评论: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],
  []
]

思路:借助排列组合的想法,本题可以解释成分别从数组S中选择1个,2个,3个......n个元素的子序列有哪些,最后在结果中加上一个空集即可。为了实现有序,可以先对输入数组S进行排序,在代码中实现了快排。
代码如下:
 1 List<List<Integer>> lists = new ArrayList<List<Integer>>();
 2     public List<List<Integer>> subsets(int[] S) {
 3         fastSortingHelp(S, 0, S.length-1);
 4         for(int i=1; i<=S.length; i++) {
 5             subsetsHelper(S, i, 0, new ArrayList<Integer>());
 6         }
 7         lists.add(new ArrayList<Integer>());
 8         return lists;
 9     }
10     
11     //快排代码
12     public void fastSortingHelp(int[] S, int start, int over) {
13         if(start >= over)
14             return;
15         int left = start;
16         int right = over;
17         int compare = start;
18         while(left < right) {
19             while(left < right && S[right] >= S[compare]) {
20                 right--;
21             }
22             int tmp = S[right];
23             S[right] = S[compare];
24             S[compare] = tmp;
25             compare = right;
26             
27             while(left < right && S[left] <= S[compare]) {
28                 left++;
29             }
30             tmp = S[left];
31             S[left] = S[compare];
32             S[compare] = tmp;
33             compare = left;
34         }
35         fastSortingHelp(S, start, left-1);
36         fastSortingHelp(S, left+1, over);
37     }
38     
39     //从数组S中,取得k个元素,这k个元素的下标都需>=start
40     public void subsetsHelper(int[] S, int k, int start, List<Integer> list) {
41         if(k == 1) {
42             for(int i=start; i<S.length; i++) {
43                 list.add(new Integer(S[i]));
44                 
45                 lists.add(new ArrayList<Integer>(list));
46                 list.remove(new Integer(S[i]));
47             }
48         } else {
49             for(int i=start; i<=S.length-k; i++) {
50                 list.add(new Integer(S[i]));
51                 subsetsHelper(S, k-1, i+1, list);
52                 list.remove(new Integer(S[i]));
53             }
54         }
55     }

 

 

问题:如果出现重复元素怎么处理?

LeetCode-78 Subsets

标签:

原文地址:http://www.cnblogs.com/linxiong/p/4295588.html

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