leetCode78. 子集
思路一:迭代法
代码
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
for(int i = 0; i < 1 << n; i++) // 1 << n = 2^n
{
vector<int> path;
for(int j = 0; j < n; j++){
if(i >> j & 1) path.push_back(nums[j]);
}
res.push_back(path);
}
return res;
}
};
方法二:经典dfs
代码
class Solution {
public:
vector<int> path;
vector<vector<int>> res;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(0,nums);
return res;
}
void dfs(int count, vector<int>& nums){
if(count == nums.size()){
res.push_back(path);
return;
}
path.push_back(nums[count]); //将该数据加进来的路径
dfs(count + 1, nums);
path.pop_back(); // 将该数据清除(不加进去)后的路径
dfs(count + 1, nums);
}
};