Subsets I
Problem link: https://leetcode.com/problems/subsets/
Constaint:
1 <= nums.length <= 10
-10 <= nums[i] <= 10
All the numbers of nums are unique.
Idea
Suppose we have a temparary list to store all the elements we processed so far. For each number at index i, we have two posibilities: 1) Add nums[i] to the list; 2) Not add nums[i] to the list. Use DFS to do this recursively for every number. The terminating condition is when the index == nums.length;
- DFS solution 1
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
search(nums, 0, new ArrayList<Integer>(), results);
return results;
}
private void search(int[] nums, int index, List<Integer> subset, List<List<Integer>> results) {
if (index == nums.length) {
results.add(new ArrayList<>(subset));
return;
}
search(nums, index + 1, subset, results);
subset.add(nums[index]);
search(nums, index + 1, subset, results);
subset.remove(subset.size() - 1);
}
}
- DFS solution 2
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
search(nums, 0, new ArrayList<Integer>(), results);
return results;
}
private void search(int[] nums, int start, List<Integer> subset, List<List<Integer>> results) {
results.add(new ArrayList<Integer>(subset));
for (int i = start; i < nums.length; i++) {
subset.add(nums[i]);
search(nums, i + 1, subset, results);
subset.remove(subset.size() - 1);
}
}
}
- Time: O(n * 2^n) as there are 2^n possible combinations, and making a copy of each subset takes O(n).
- Space: O(n). The recursion stack will be as large as the size of array.
Related question:
- Subsets II
浙公网安备 33010602011771号