Description
Submission
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<int> curr;
vector<vector<int>> res;
powerset(nums, curr, nums.size() - 1, res);
return res;
}
private:
void powerset(vector<int>& nums, vector<int> curr, int index, vector<vector<int>>& res) {
if(index == 0) {
res.push_back(curr);
curr.push_back(nums[0]);
res.push_back(curr);
return;
}
powerset(nums, curr, index - 1, res);
curr.push_back(nums[index]);
powerset(nums, curr, index - 1, res);
}
};
Submission 200912
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> hand;
backtrack(nums, res, hand, 0);
return res;
}
private:
void backtrack(vector<int>& nums, vector<vector<int>>& res, vector<int>& hand, int k) {
if(k == nums.size()) {
res.push_back(hand);
return;
}
// without the number
backtrack(nums, res, hand, k+1);
hand.push_back(nums[k]);
// with the number
backtrack(nums, res, hand, k+1);
// back to original state
hand.pop_back();
}
};