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], [] ]
AC code:
class Solution { public: vector<vector<int>> subsets(vector<int>& nums) { vector<vector<int>> res; vector<int> temp; int len = nums.size(); solve_subset(0, len, res, temp, nums); return res; } void solve_subset(int begin, int n, vector<vector<int>>& res, vector<int>& temp, vector<int>& nums) { res.push_back(temp); for (int i = begin; i < n; ++i) { temp.push_back(nums[i]); solve_subset(i+1, n, res, temp, nums); temp.pop_back(); } } };
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Subsets.