LeetCode - Subsets

less than 1 minute read

Problem description

description

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

1
2
3
4
5
6
7
8
9
10
11
12
Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

Analysis

The general idea is to use backtrack.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
    public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        
        backtrack(res, new ArrayList<>(), 0, nums);
        return res;
    }
    
    void backtrack(List<List<Integer>> res, List<Integer> list, int start, int[] nums){
        if (start > nums.length){
            return;
        }
        
        res.add(new ArrayList(list));
        
        for (int i = start; i < nums.length; i++){
            list.add(nums[i]);
            backtrack(res, list, i+1, nums);
            list.remove(list.size() -1 );
        }
    }
}

What to improve