Subsets — LeetCode
Problem 61: Subsets
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.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]Example 2:
Input: nums = [0]
Output: [[],[0]]Approach
Use recursion to form all possible subsets and push it to a final output array.
Solution design
Finding all subsets can be broken down into two decisions. To take the number, or not to take it. The recursive tree diagram illustrates this. Starting with 1, we make 2 recursion calls, one which pushes 1 into its subset, and another that does not, indicated by the empty list.
Let’s focus on one branch of the tree. The next 2 paths to be made is to push 2 into the subset, or not push 2 into the subset.
Continue sticking to the left branch, we perform the same operation, of pushing 3 into the subset, or not. At this point, we have come to the end of the nums array, and we can push this subset to the final output array as one of the many subsets.
The diagram has only focused on one branch. But this process is replicated throughout the tree at different branches, giving us a final tree like this.
Code implementation
The stopping criteria of the recursion function is the length of the array of possible number choices.
Get Zhen Yang’s stories in your inbox
Join Medium for free to get updates from this writer.
First we perform the first decision of pushing the number to the current array. Then we make a recursive call with this subset, while also removing the added number from the list of possible choices.
Next, we pop() from the subset as we move on to the second decision, choosing not to add the number to the subset. We make a new recursive call with this subset, while also removing the added number from the list of possible choices.
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
let output = [];
const subset = (curr, remaining) => {
if (remaining.length === 0) {
output.push([...curr]);
return;
}
curr.push(remaining[0]);
subset(curr, remaining.slice(1));
curr.pop();
subset(curr, remaining.slice(1));
};
subset([], nums);
return output;
};This solution got me a 0ms runtime which beats 100.00% of submissions🎉😃!
Thank you for reading my article 🙏. Happy coding!







