78. Subsets
https://leetcode.com/problems/subsets/description/
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]Thoughts
Code
Analysis
Last updated
https://leetcode.com/problems/subsets/description/
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]Last updated
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res = []
def dfs(pos, res, path):
for i in range(pos, len(nums)):
path.append(nums[i])
dfs(i + 1, res, path)
path.pop()
res.append([i for i in path])
dfs(0, res, [])
return res
class Solution {
private void helper(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]);
helper(nums, i + 1, path, res);
path.remove(path.size() - 1);
}
}
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
helper(nums, 0, new ArrayList<>(), res);
return res;
}
}