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

lintcode-medium-Subsets

时间:2016-04-07 07:06:36      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Given a set of distinct integers, return all possible subsets.

 

Notice
  • Elements in a subset must be in non-descending order.
  • The solution set must not contain duplicate subsets.
Example

If S = [1,2,3], a solution is:

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

Can you do it in both recursively and iteratively?

 

class Solution {
    /**
     * @param S: A set of numbers.
     * @return: A list of lists. All valid subsets.
     */
    public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
        // write your code here
        
        ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
        //res.add(new ArrayList<Integer>());
        
        ArrayList<Integer> line = new ArrayList<Integer>();
        Arrays.sort(nums);
        
        for(int i = 0; i <= nums.length; i++){
            helper(res, line, i, 0, nums);
        }
        
        return res;
    }
    
    public void helper(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> line, int len, int start, int[] nums){
        
        if(line.size() == len){
            res.add(new ArrayList<Integer>(line));
            return;
        }
        
        for(int i = start; i < nums.length; i++){
            line.add(nums[i]);
            helper(res, line, len, i + 1, nums);
            line.remove(line.size() - 1);
        }
        
        return;
    }
    
}

 

lintcode-medium-Subsets

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5361951.html

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