# 12-line C++ DFS

• ``````class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
set<vector<int>> res; // use set to filter out duplicates
DFS(nums,0,new vector<int>(),res);
return vector<vector<int>>(res.begin(),res.end());
}

void DFS(vector<int>& nums, int index, vector<int>* cur, set<vector<int>>& res) {
cur->size()>=2? res.insert({*cur}) : (void)0;
for(int i=index;i<nums.size();i++)
if(cur->empty() || nums[i]>=cur->back()) {
cur->push_back(nums[i]);
DFS(nums,i+1,cur,res);
cur->pop_back();
}
}
};
``````

• @luming89 said in 12-line C++ DFS:

class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
set<vector<int>> res; // use set to filter out duplicates
DFS(nums,0,new vector<int>(),res);
return vector<vector<int>>(res.begin(),res.end());
}

``````void DFS(vector<int>& nums, int index, vector<int>* cur, set<vector<int>>& res) {
cur->size()>=2? res.insert({*cur}) : (void)0;
for(int i=index;i<nums.size();i++)
if(cur->empty() || nums[i]>=cur->back()) {
cur->push_back(nums[i]);
DFS(nums,i+1,cur,res);
cur->pop_back();
}
}
``````

};

Thanks for your elegant solution.

If "cur" is not a pointer (i.e. a vector reference), then the program runs faster... I am still curious that you use a pointer instead.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.