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

[leetcode] Subsets

时间:2014-07-07 14:31:24      阅读:164      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   java   color   

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

https://oj.leetcode.com/problems/subsets/

 

思路:递归构造,每一层递归都选择填或者不填s[cur]的操作。

bubuko.com,布布扣
import java.util.ArrayList;
import java.util.Arrays;

public class Solution {
    public ArrayList<ArrayList<Integer>> subsets(int[] S) {
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        ArrayList<Integer> tmp = new ArrayList<Integer>();
        Arrays.sort(S);
        subsetsHelper(res, tmp, S, 0);
        return res;
    }

    private void subsetsHelper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int[] s, int cur) {
        if (cur == s.length) {
            res.add(new ArrayList<Integer>(tmp));
            return;
        }

        // not fill
        subsetsHelper(res, tmp, s, cur + 1);

        // fill
        tmp.add(s[cur]);
        subsetsHelper(res, tmp, s, cur + 1);
        tmp.remove(tmp.size() - 1);

    }

    public static void main(String[] args) {
        System.out.println(new Solution().subsets(new int[] { 4, 1, 0 }));
    }
}
View Code

 

 

 

 

[leetcode] Subsets,布布扣,bubuko.com

[leetcode] Subsets

标签:des   style   blog   http   java   color   

原文地址:http://www.cnblogs.com/jdflyfly/p/3815295.html

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