Given a set of distinct integers, nums, return all possible subsets.
Note:
For example,
If nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Analyse: Each number has two states: selected or not selected. Recursively invoke the choose function until the step equals to the size. Then construct a vector to store all selected numbers, and push it to the result vector.
Runtime: 8ms.
1 class Solution { 2 public: 3 vector<vector<int>> subsets(vector<int>& nums) { 4 vector<vector<int> > result; 5 sort(nums.begin(), nums.end()); 6 vector<bool> selected(nums.size(), false); 7 subset(nums, selected, 0, result); 8 9 return result; 10 } 11 12 void subset(vector<int> &nums, vector<bool> &selected, int step, vector<vector<int> > &result){ 13 if(step == nums.size()){ 14 vector<int> temp; 15 for(int i = 0; i < step; i++){ 16 if(selected[i]) temp.push_back(nums[i]); 17 } 18 result.push_back(temp); 19 return; 20 } 21 22 //not choose the number 23 selected[step] = false; 24 subset(nums, selected, step + 1, result); 25 //choose the number 26 selected[step] = true; 27 subset(nums, selected, step + 1, result); 28 } 29 };