地址:https://leetcode.com/problems/subsets/
题目:
Given a set of distinct integers, n u m s nums nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
理解:
用backtracking解决。
实现:
和前面的不太一样的是,这里每次调用dfs直接把tmp加进去就好了,因为所有大小的子集都要包含在里面。不需要判断tmp和目标集合大小是否相同。
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> tmp;
dfs(res, tmp, nums, 0);
return res;
}
private:
void dfs(vector<vector<int>>& res, vector<int>& tmp, vector<int>& nums, int begin) {
res.push_back(tmp);
for (int i = begin; i<nums.size(); ++i) {
tmp.push_back(nums[i]);
dfs(res, tmp, nums, i + 1);
tmp.pop_back();
}
}
};