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

LeetCode 78: Subsets

时间:2017-08-22 13:52:22      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:remove   subsets   last   streaming   ret   private   lis   log   art   

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        result.add(new ArrayList<>());
        
        if (nums.length == 0) {
            return result;
        }
        
        for (int num : nums) {
            List<List<Integer>> newResult = new ArrayList<>(result);
            for (List<Integer> row : result) {
                List<Integer> newRow = new ArrayList<>(row);
                newRow.add(num);
                newResult.add(newRow);
            }
            result = newResult;
        }
        return result;
    }
}

 

 

For streaming processing, we could use number to set as recorder of last state.

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();        
        
        long recorder = 0;
        long bound = (1 << nums.length) - 1;
        while (recorder <= bound) {
            result.add(toNum(recorder++, nums));
        }
        return result;
    }
    
    private List<Integer> toNum(long recorder, int[] nums) {
        List<Integer> result = new ArrayList<>();
        int i = nums.length - 1;
        while (i >= 0) {
            if ((recorder & 1L) == 1L) {
                result.add(nums[i]);
            }
            recorder >>= 1;
            i--;
        }
        return result;
    }
}

 

Normal recursion:

class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();        
        result.add(new ArrayList<>());
        helper(result, 0, new ArrayList<>(), nums);
        return result;
    }
    
    private void helper(List<List<Integer>> result, int start, List<Integer> current, int[] nums) {
        if (start == nums.length) {
            return;
        }
        
        for (int i = start; i < nums.length; i++) {
            current.add(nums[i]);
            result.add(new ArrayList<>(current));
            helper(result, i + 1, current, nums);
            current.remove(current.size() - 1);
        }
    }
}

 

LeetCode 78: Subsets

标签:remove   subsets   last   streaming   ret   private   lis   log   art   

原文地址:http://www.cnblogs.com/shuashuashua/p/7411119.html

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