
Sponsored
Sponsored
This approach utilizes the concept of recursive backtracking to explore all potential subsets. We start with an empty list and progressively build subsets by either including or excluding each element.
Time Complexity: O(2^n * n), where n is the length of nums. We have 2^n subsets, and copying each subset takes O(n).
Space Complexity: O(n), where n is the depth of the recursion stack.
1const subsets = (nums) => {
2 const result = [];
3 const backtrack = (index, current) => {
4 result.push([...current]);
5 for (let i = index; i < nums.length; i++) {
6 current.push(nums[i]);
7 backtrack(i + 1, current);
8 current.pop();
9 }
10 };
11 backtrack(0, []);
12 return result;
13};
14
15const nums = [1, 2, 3];
16console.log(subsets(nums));
17This JavaScript implementation utilizes closure and recursion to achieve subset generation. The 'backtrack' function maintains an ongoing state of recursion depth and utilises backtracking to manage element inclusions/exclusions
This approach takes advantage of bit manipulation to enumerate subsets. Each subset can correspond to a binary number where each bit decides if an element is present in the subset:
Time Complexity: O(2^n * n), mapping to subset enumeration.
Space Complexity: O(1), as it utilizes constants.
1#include <iostream>
2#include <vector>
std::vector<std::vector<int>> subsets(const std::vector<int>& nums) {
int subsetCount = 1 << nums.size();
std::vector<std::vector<int>> result;
for (int i = 0; i < subsetCount; ++i) {
std::vector<int> subset;
for (int j = 0; j < nums.size(); ++j) {
if (i & (1 << j)) {
subset.push_back(nums[j]);
}
}
result.push_back(subset);
}
return result;
}
int main() {
std::vector<int> nums = {1, 2, 3};
std::vector<std::vector<int>> result = subsets(nums);
for (const auto& subset : result) {
std::cout << "[";
for (int num : subset) {
std::cout << num << " ";
}
std::cout << "]\n";
}
return 0;
}
This implementation in C++ applies bit manipulation where 'subsetCount' stands as a numeric representation total for all subsets. Bitwise logic determines element integration within subsequent subsets.