Problem
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Solution (Java)
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
solve(nums, new ArrayList<>(), res, 0);
return res;
}
private void solve(int[] nums, List<Integer> temp, List<List<Integer>> res, int start) {
res.add(new ArrayList<>(temp));
for (int i = start; i < nums.length; i++) {
temp.add(nums[i]);
solve(nums, temp, res, i + 1);
temp.remove(temp.size() - 1);
}
}
}
Solution (Javascript)
/**
* @param {number[]} nums
* @return {number[][]}
*/
var subsets = function(nums) {
var res = [];
helper(nums, res, [], 0);
return res;
};
var helper = function (nums, res, arr, start) {
var len = nums.length;
res.push(Array.from(arr));
if (start === len) return;
for (var i = start; i < len; i++) {
arr.push(nums[i]);
helper(nums, res, arr, i + 1);
arr.pop();
}
};
Explain:
nope.
Complexity:
- Time complexity :
- Space complexity :