子集问题就是组合问题
- 无序 for从start开始
- 记录每一个节点 那么 dfs 开头就是 result.push_back(path)
- 有重复元素, 那么就是同层去重
class Solution {
public:
vector<int>path;
vector<vector<int>>result;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(nums, 0);
return result;
}
void dfs(vector<int>&nums, int start){
result.push_back(path);
for(int i = start; i<nums.size(); i++){
path.push_back(nums[i]);
dfs(nums, i+1);
path.pop_back();
}
}
};
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
vector<vector<int>> subsets(vector<int>& nums) {
dfs(nums, 0);
return result;
}
void dfs(vector<int>& nums, int start){
if(start >= nums.size()){
result.push_back(path);
return;
}
path.push_back(nums[start]);
dfs(nums, start+1);
path.pop_back();
dfs(nums, start+1);
}
};
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
dfs(nums, 0);
return result;
}
void dfs(vector<int>& nums, int start){
result.push_back(path);
for(int i=start; i<nums.size(); i++){
if(start < i && nums[i]==nums[i-1]) continue;
path.push_back(nums[i]);
dfs(nums, i+1);
path.pop_back();
}
}
};
class Solution {
public:
vector<vector<int>>result;
vector<int>path;
vector<vector<int>> findSubsequences(vector<int>& nums) {
dfs(nums, 0);
return result;
}
void dfs(vector<int>& nums, int start){
if(path.size() >= 2) result.push_back(path);
unordered_map<int, bool>mp;
for(int i=start; i<nums.size(); i++){
if(mp.find(nums[i])!=mp.end()) continue; //在同一层这个数已经用过了
mp[nums[i]] = true;
if(path.size()==0 || nums[i] >= path[path.size()-1]){
path.push_back(nums[i]);
dfs(nums, i+1);
path.pop_back();
}
}
}
};