Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example :

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

solution

time complexity : O(2^n)
space complexity : O(2^n)
(n : nums size)

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans;
        
        for (int i=0; i<=nums.size(); ++i) {
            dfs(nums, i, 0, {}, ans);
        }
        
        return ans;
    }
private:
    void dfs(vector<int> nums, int size, int pos, vector<int> cur, vector<vector<int>>& ans) {
        if (cur.size() == size) {
            ans.push_back(cur);
            return;
        }
        
        for (int i=pos; i<nums.size(); ++i) {
            cur.push_back(nums[i]);
            dfs(nums, size, i+1, cur, ans);
            cur.pop_back();
        }
    }
};

根據子集大小的數量(1~n個),個別求其組合。
若目前子集內元素數目=目標子集量,就塞入答案中。
沒有的話,就加入下一個元素到目前子集內。