Grokking the Coding Interview: Patterns for Coding Questions
0% completed
Subsets (easy)
Problem Statement
Given a set with distinct elements, find all of its distinct subsets.
Example 1:
Input: [1, 3]
Output: [], [1], [3], [1,3]
Example 2:
Input: [1, 5, 3]
Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3]
Constraints:
1 <= nums.length <= 10-10 <= nums[i] <= 10- All the numbers of nums are
unique.
Try it yourself
Try solving this question here:
.....
.....
.....
Like the course? Get enrolled and start learning!
Trang Luong
· a year ago
class Solution: # cascading, at each step, add the number to all current subsets # If it's a list of list, make sure copy each time or else it will modify reference # def find_subsets(self, nums): # subsets = [[]] # #[1, 2, 3] # for num in nums: # subsets_copy = subsets.copy() # O(n) # for subset in subsets_copy: # O(2^n) (k start with 1 and grow until 2^n for n) # new_subnet = subset.copy() # O(N) # new_subnet.append(num) # subsets.append(new_subnet) # return subsets def find_subsets(self, nums): result_subsets = [] self.backtrack(0, [], result_subsets, nums) return result_subsets # Backtracking solution, building each solution as we go down a tree of decision to build subset # backtrack(0, [], [],