The algorithm follows recursive approach, dividing the array in two parts:
- In first recursion the first part is neglected
- In second part the first part is added
Code for C++ (Works Fine)
JavaScript
x
30
30
1
class Solution {
2
public:
3
4
vector<vector<int>> result;
5
6
void get_set(vector<int>& nums, vector<int> res, int index=0)
7
{
8
if(index == nums.size())
9
{
10
result.push_back(res);
11
return;
12
}
13
14
int top = nums[index++];
15
16
get_set(nums, res, index);
17
res.push_back(top);
18
get_set(nums, res, index);
19
}
20
21
vector<vector<int>> subsets(vector<int>& nums)
22
{
23
vector<int> res;
24
25
get_set(nums, res);
26
27
return result;
28
}
29
};
30
Code for Python
JavaScript
1
19
19
1
class Solution:
2
def __init__(self):
3
self.result = [[]]
4
5
def get_subsets(self, arr, temp=[], index=0):
6
if(index==len(arr)):
7
self.result.append(temp)
8
return
9
top = arr[index]
10
index+=1
11
12
self.get_subsets(arr, temp, index)
13
temp.append(top)
14
self.get_subsets(arr, temp, index)
15
16
def subsets(self, nums: List[int]) -> List[List[int]]:
17
self.get_subsets(nums)
18
return self.result
19
Advertisement
Answer
In the C++ version, res
is a by-value parameter, so a copy of the vector is made in each call. Python passes references to the list, so you keep modifying the same temp
list throughout the algorithm. Pass a copy when you make the recursive calls.
There’s also no need for an empty nested list in the initial value of self.result
. The C++ version starts with an empty vector.
JavaScript
1
21
21
1
class Solution:
2
def __init__(self):
3
self.result = []
4
5
def get_subsets(self, arr, temp=None, index=0):
6
if temp is None:
7
temp = []
8
if(index==len(arr)):
9
self.result.append(temp)
10
return
11
top = arr[index]
12
index+=1
13
14
self.get_subsets(arr, temp.copy(), index)
15
temp.append(top)
16
self.get_subsets(arr, temp.copy(), index)
17
18
def subsets(self, nums: List[int]) -> List[List[int]]:
19
self.get_subsets(nums)
20
return self.result
21