LeetCode 78: Subsets

Posted keepshuatishuati

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 78: Subsets相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 78: Subsets

Leetcode 78. Subsets

Leetcode 78. Subsets

[leetcode-78-Subsets]

Leetcode 78: Subsets

LeetCode78. Subsets