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

leetcode------Subsets

时间:2015-03-16 16:20:18      阅读:82      评论:0      收藏:0      [点我收藏+]

标签:

标题: Subsets
通过率: 28.2%
难度: 中等

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],
  []
]

本题思路就是找出所有子集,具体看代码:

 1 public class Solution {
 2 
 3     ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
 4     
 5     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 6         Arrays.sort(S);
 7         // length of subsets: from 0 to S.length
 8         for (int i = 0; i <= S.length; i++) {
 9             backTracking(new ArrayList<Integer>(), 0, i,S);
10         }
11         return ans;
12     }
13     
14     public void backTracking(ArrayList<Integer> list, int from, int tar,int[] S) {
15         if (list.size() == tar) {
16             ArrayList<Integer> res = new ArrayList<Integer>(list);
17             ans.add(res);
18         } else {
19             for (int i = from; i < S.length; i++) {
20                 list.add(S[i]);
21                 backTracking(list, i + 1, tar,S);
22                 list.remove(list.size()-1);
23             }
24         }
25     }
26 }

 

leetcode------Subsets

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4341947.html

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