Subsets

Description

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],
  []
]

Solutions

My solution

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ans(1);
        for(int num : nums){
            int size = ans.size();
            for(int i = 0; i < size; ++i){
                vector<int> subset = ans[i];
                subset.push_back(num);
                ans.push_back(subset);
            }
        }
        return ans;
    }
};

Recursive solution

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<int> acc;
        vector<vector<int>> ans;
        dfs(nums, 0, acc, ans);
        return ans;
    }
    
    void dfs(vector<int> &nums, int start, vector<int> &acc, vector<vector<int>> &ans){
        ans.push_back(acc);
        for(int i = start; i < nums.size(); ++i){
            acc.push_back(nums[i]); // use nums[i]
            dfs(nums, i + 1, acc, ans);
            acc.pop_back(); // not use nums[i]
        }
    }
};

Last updated