s0216
This commit is contained in:
parent
72eb7d55ef
commit
30d9599c39
13
include/s0216_combination_sum_iii.hpp
Normal file
13
include/s0216_combination_sum_iii.hpp
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef S0216_COMBINATION_SUM_III_HPP
|
||||
#define S0216_COMBINATION_SUM_III_HPP
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class S0216 {
|
||||
public:
|
||||
vector<vector<int>> combinationSum3(int k, int n);
|
||||
};
|
||||
|
||||
#endif
|
@ -68,3 +68,7 @@ void combineDFS(int n, int k, int begin, vector<int> &path,
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/)
|
||||
|
||||
|
||||
|
27
src/s0216_combination_sum_iii.cpp
Normal file
27
src/s0216_combination_sum_iii.cpp
Normal file
@ -0,0 +1,27 @@
|
||||
#include "s0216_combination_sum_iii.hpp"
|
||||
|
||||
void combinationSum3DFS(int k, int n, int begin, vector<int> &path, int sum,
|
||||
vector<vector<int>> &result) {
|
||||
// 终止条件:高度达到上限且总和为 n
|
||||
if (path.size() == k && sum == n) {
|
||||
result.push_back(path);
|
||||
return;
|
||||
}
|
||||
|
||||
// 开始迭代
|
||||
// 当总和 > n 时,剪枝
|
||||
for (int i = begin; i <= 9 && sum + i <= n; ++i) {
|
||||
sum += i;
|
||||
path.push_back(i);
|
||||
combinationSum3DFS(k, n, i + 1, path, sum, result);
|
||||
sum -= i;
|
||||
path.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
vector<vector<int>> S0216::combinationSum3(int k, int n) {
|
||||
vector<int> path{};
|
||||
vector<vector<int>> result;
|
||||
combinationSum3DFS(k, n, 1, path, 0, result);
|
||||
return result;
|
||||
}
|
Loading…
Reference in New Issue
Block a user