This commit is contained in:
27
src/s0077_combinations.cpp
Normal file
27
src/s0077_combinations.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
#include "s0077_combinations.hpp"
|
||||
|
||||
void combineDFS(int n, int k, int begin, vector<int> &path,
|
||||
vector<vector<int>> &result) {
|
||||
// 当 path 长度等于 k 时停止迭代,并将加入结果
|
||||
if (path.size() == k) {
|
||||
result.push_back(path);
|
||||
return;
|
||||
}
|
||||
|
||||
// 遍历可能的搜索起点
|
||||
for (int i = begin; i <= n; ++i) {
|
||||
// 将 i 加入路径
|
||||
path.push_back(i);
|
||||
// 下一轮搜索
|
||||
combineDFS(n, k, i + 1, path, result);
|
||||
// 回溯,撤销处理的节点
|
||||
path.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
vector<vector<int>> S0077::combine(int n, int k) {
|
||||
vector<vector<int>> result;
|
||||
vector<int> path;
|
||||
combineDFS(n, k, 1, path, result);
|
||||
return result;
|
||||
}
|
Reference in New Issue
Block a user