78. Subsets

# Medium

Subset problems are generally solved by RECURSIVE.

Recursive process for array [1, 2, 3]
class Solution {
    List<List<Integer>> res = new ArrayList<List<Integer>>();
    
    public List<List<Integer>> subsets(int[] nums) {
        ArrayList<Integer> level = new ArrayList<Integer>();
        helper(nums, 0, level);
        return res;
    }
    
    public void helper(int[] nums, int i, ArrayList<Integer> level) {
        res.add(new ArrayList(level));  // copy level to res
        if(i == nums.length) return;
        
        for(int j = i; j < nums.length; j ++) {
            level.add(nums[j]);
            helper(nums, j + 1, level);
            level.remove(level.size() - 1);
        }
    }
}

Time complexity = O(n2n)O(n*2^n) , nn is to copy the subset to result.

Space complexity = O(n2n)O(n*2^n)

Last updated

Was this helpful?