力扣78题
作者:互联网
方法一: binary 不使用递归
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
int n = nums.size();
for (int i = 0; i < 1 << n; i ++ ) {
vector<int> path;
for (int j = 0; j < n; j ++) {
if (i >> j & 1) path.push_back(nums[j]);
}
ans.push_back(path);
}
return ans;
}
};
方法二:DFS+backing
- 递归树很重要,之前以为简单,但是发现代码不会写才发现递归树已经蕴含了很多自己不懂的东西
//DFS + back-tracing
//learn from huahua
class Solution {
private:
void dfs(vector<int>& nums, int n, int s, vector<int>& cur, vector<vector<int>>& ans) {
if (n == cur.size()) {
ans.push_back(cur);
// <debug>
cout << "ans is "<<' ';
for (int i = 0; i < cur.size(); i ++ ) {
cout << cur[i] <<' ';
}
cout << endl;
// </debug>
return ;
}
for (int i = s; i < nums.size(); ++ i) {
cur.push_back(nums[i]);
dfs(nums, n, i + 1, cur, ans);
cur.pop_back();
}
// 错误代码
/*
这样的话 递归树就少了好几条路径, 还是要把递归树画出来才可以
cur.push_back(nums[s]);
dfs(nums, n, s + 1, cur, ans);
cur.pop_back();
*/
}
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> ans;
vector<int> cur;
for (int i = 0; i <= nums.size(); i ++ ) {
dfs(nums, i, 0, cur, ans);
}
return ans;
}
};
标签:cur,nums,int,back,力扣,vector,ans,78 来源: https://www.cnblogs.com/yueming/p/16207256.html