回溯题,先画二叉树。还是有一个去重的问题。
回溯三部曲
1、函数参数
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex);
2、终止条件
if (path.size() > 1) {
result.push_back(path);
}
3、单层逻辑
unordered_set<int> used;//每层都重新定义,保证了只在单层看重复值
for (int i = startIndex; i < nums.size(); i++) {
if ((!path.empty() && path.back() > nums[i]) || (used.find(nums[i]) != used.end()) {
continue;
}
used.insert(nums[i]);
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
完整代码
class Solution {
private:
vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& nums, int startIndex) {
if (path.size() > 1) {
result.push_back(path);
}
unordered_set<int> uset;
for (int i = startIndex; i < nums.size(); i++) {
if ((!path.empty() && nums[i] < path.back()) || (uset.find(nums[i]) != uset.end())) {
continue;
}
uset.insert(nums[i]);
path.push_back(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
result.clear();
path.clear();
backtracking(nums, 0);
return result;
}
};