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], [] ]
求一个集合的所有子集,高中就知道所有子集个数为$2^n$个,包括空集和它本身。
算法思路和LeetCode Combinations几乎一样,只不过成功条件不再是candidate中有k个数了,而是每添加一个元素都算成功一个。
完整代码如下:
class Solution {
public:
void work(vector<vector<int> >& ans, vector<int>& cand, vector<int>& nums, int step)
{
ans.push_back(cand);
for (int i = step; i < nums.size(); i++) {
cand.push_back(nums[i]);
work(ans, cand, nums, i + 1);
cand.pop_back();
}
}
vector<vector<int> > subsets(vector<int>& nums)
{
vector<vector<int> > ans;
vector<int> cand;
work(ans, cand, nums, 0);
return ans;
}
};
本代码提交AC,用时3MS。
Pingback: LeetCode Subsets II | bitJoy > code