78. Subsets
Asked at 19Bloomberg70Amazon65Meta64Microsoft59Google52Apple22Agoda57Infosys39Coupang97PornHub87Wix70Uber52PayPal51TikTok50Flipkart43Walmart Labs43tcs42Oracle27Goldman Sachs21
Problem
nums holds distinct integers. Return every subset (the power set), in any order, with no duplicate subsets.
Example: [1,2,3] → [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Constraints: n ≤ 10.
Every node of the decision tree is a subset — record the path on entry.
Complexity: O(n · 2ⁿ).
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res, path = [], []
def bt(start):
res.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
bt(i + 1)
path.pop()
bt(0)
return res
assert sorted(map(sorted, Solution().subsets([1, 2, 3]))) == sorted(map(sorted, [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]))
assert sorted(map(sorted, Solution().subsets([0]))) == [[], [0]]
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
bt(nums, 0, new ArrayList<>(), res);
return res;
}
private void bt(int[] nums, int start, List<Integer> path, List<List<Integer>> res) {
res.add(new ArrayList<>(path));
for (int i = start; i < nums.length; i++) {
path.add(nums[i]);
bt(nums, i + 1, path, res);
path.remove(path.size() - 1);
}
}
}
func subsets(nums []int) [][]int {
res, path := [][]int{}, []int{}
var bt func(start int)
bt = func(start int) {
res = append(res, append([]int{}, path...)) // every node of the tree is a subset
for i := start; i < len(nums); i++ {
path = append(path, nums[i])
bt(i + 1)
path = path[:len(path)-1]
}
}
bt(0)
return res
}