Overview
Given an integer array nums of unique elements, return all possible subsets (the power set). No duplicate subsets.
Constraints
1 <= nums.length <= 10-10 <= nums[i] <= 10- All elements are unique.
Examples
subsets([1, 2, 3]); // => [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]]
Solution
Reveal solution
function subsets(nums) {
const result = [];
function backtrack(start, path) {
result.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}Resources
subsets.js
Subsets
mediumcodingAlgorithmsBacktracking
Overview
Given an integer array nums of unique elements, return all possible subsets (the power set). No duplicate subsets.
Constraints
1 <= nums.length <= 10-10 <= nums[i] <= 10- All elements are unique.
Examples
subsets([1, 2, 3]); // => [[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]]
Solution
Reveal solution
function subsets(nums) {
const result = [];
function backtrack(start, path) {
result.push([...path]);
for (let i = start; i < nums.length; i++) {
path.push(nums[i]);
backtrack(i + 1, path);
path.pop();
}
}
backtrack(0, []);
return result;
}Resources
NameTopicDifficulty
103 of 103 problems