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)
class Solution {
public:
vector<vector<int>> result;
void get_set(vector<int>& nums, vector<int> res, int index=0)
{
if(index == nums.size())
{
result.push_back(res);
return;
}
int top = nums[index++];
get_set(nums, res, index);
res.push_back(top);
get_set(nums, res, index);
}
vector<vector<int>> subsets(vector<int>& nums)
{
vector<int> res;
get_set(nums, res);
return result;
}
};
Code for Python
class Solution:
def __init__(self):
self.result = [[]]
def get_subsets(self, arr, temp=[], index=0):
if(index==len(arr)):
self.result.append(temp)
return
top = arr[index]
index+=1
self.get_subsets(arr, temp, index)
temp.append(top)
self.get_subsets(arr, temp, index)
def subsets(self, nums: List[int]) -> List[List[int]]:
self.get_subsets(nums)
return self.result