This commit is contained in:
Sainnhe Park 2023-02-02 10:14:39 +08:00
parent 72eb7d55ef
commit 30d9599c39
3 changed files with 44 additions and 0 deletions

View 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

View File

@ -68,3 +68,7 @@ void combineDFS(int n, int k, int begin, vector<int> &path,
} }
} }
``` ```
## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/)

View 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;
}