78. Subsets

Problem:

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:

class Solution {
public:
    vector<vector<int>> subsets(vector<int>& nums) {
        vector<vector<int>> ret;
        vector<int> path;
        helper(nums, 0, path, ret);
        return ret;
    }

    void helper(vector<int>& nums, int pos, vector<int>& path, vector<vector<int>>& ret) {
        if (pos == nums.size()) {
            ret.push_back(path);
            return;
        }

        path.push_back(nums[pos]);
        helper(nums, pos + 1, path, ret);
        path.pop_back();

        helper(nums, pos + 1, path, ret);
    }
};

results matching ""

    No results matching ""