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],
[]
]
思路:
采用递归的思想。首先设一个包含空vector
Solution:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res = {{}};
for (int num : nums) {
int n = res.size();
for (int i = 0; i < n; i++) {
res.push_back(res[i]);
res.back().push_back(num);
}
}
return res;
}
性能:
Runtime: 4 ms Memory Usage: 9.1 MB