基本:
每一个元素要还是不要,所以总共2^n个subsets
解法一:BFS non-recursion
use an extra vector
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
res.push_back({});
for(int i=0;i<nums.size();i++){
vector<vector<int>> t(res.begin(), res.end());
for(int j=0;j<res.size();j++){
res[j].push_back(nums[i]); //add the new element to the old ones
}
res.insert(res.end(), t.begin(), t.end()); //replicate the old elements
}
return res;
}
};
优化:
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
res.push_back({});
for(int i=0;i<nums.size();i++){
int s = res.size();
for(int j=0;j<s;j++){
res.push_back(res[j]); //replicate the old element
res[j].push_back(nums[i]); //add a new element to the old one
}
}
return res;
}
};
理解一:
规律 -- 一开始就存在空集。处理第一个元素的时候,保留空集,增加一个新的元素(空集加第一个元素)。第二轮,前面所有的答案元素保留,并加上所有答案元素外加第二个元素。以此类推~~~
【】
1
2,【1,2】
3,【1,3】,【2,3】【1,2,3】
理解二:
每增加一个元素,总subset数增加一倍。之前存在的所有元素就是没有新元素的,之后增加的就是有新元素的。
理解三:BFS
解法二:DFS recursion
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
vector<int> out;
gen(nums, 0, out, res);
return res;
}
void gen(vector<int>& nums, int pos, vector<int>& out, vector<vector<int>>& res){
res.push_back(out);
for(int i=pos;i<nums.size();i++){
out.push_back(nums[i]);
gen(nums, i+1, out, res); //要
out.pop_back(); //不要
}
}
};
题目特征
1.求多个答案 (compare Sudoku Solver --> only need one solution )
2.不求最终答案(not fixed size) -- end cases (compare Combinations --> need final solutions)
recursion function
1. vector<int>& nums -- original input
2. int pos -- where you are at
3. vector<int>& out -- generating the solution
4. vector<vector<int>>& res -- collect the solutions
解法三:binary number
class Solution {
public:
vector<vector<int>> subsets(vector<int>& nums) {
vector<vector<int>> res;
int max = 1<<nums.size();
for(int i=0;i<max;i++){
vector<int> out = convert(nums, i);
res.push_back(out);
}
return res;
}
vector<int> convert(vector<int>& nums, int in){
vector<int> res;
int i=0;
for(int k=in; k>0;k>>=1){
if((k&1)==1){
res.push_back(nums[i]);
}
i++;
}
return res;
}
};