Posts Subsets
Post
Cancel

Subsets

Problem Description

Given an integer array nums of unique elements, return all possible subsets (the power set).

The solution set must not contain duplicate subsets. Return the solution in any order.

leetcode

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    
    List<List<Integer>> ans = new ArrayList<>();

    
    public List<List<Integer>> subsets(int[] nums) {
        find(nums, 0, new ArrayList<>());
        return ans;
    }
    
    public void find(int[] nums, int i, List<Integer> list){
        
        if(i == nums.length){
            ans.add(new ArrayList<>(list));
            return;
        }
        
        //Including
        list.add(nums[i]);
        find(nums, i+1, list);
        
        //Backtrack
        list.remove(list.size()-1);
        
        //Excluding
        find(nums, i+1, list);
        
    }
    
    
}
This post is licensed under CC BY 4.0 by the author.