From 30d9599c39d6a05af75f6284f80083c12802c3aa Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Thu, 2 Feb 2023 10:14:39 +0800 Subject: [PATCH] s0216 --- include/s0216_combination_sum_iii.hpp | 13 +++++++++++++ notes/src/combinations.md | 4 ++++ src/s0216_combination_sum_iii.cpp | 27 +++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) create mode 100644 include/s0216_combination_sum_iii.hpp create mode 100644 src/s0216_combination_sum_iii.cpp diff --git a/include/s0216_combination_sum_iii.hpp b/include/s0216_combination_sum_iii.hpp new file mode 100644 index 0000000..f92a672 --- /dev/null +++ b/include/s0216_combination_sum_iii.hpp @@ -0,0 +1,13 @@ +#ifndef S0216_COMBINATION_SUM_III_HPP +#define S0216_COMBINATION_SUM_III_HPP + +#include + +using namespace std; + +class S0216 { + public: + vector> combinationSum3(int k, int n); +}; + +#endif diff --git a/notes/src/combinations.md b/notes/src/combinations.md index 77e724d..db26057 100644 --- a/notes/src/combinations.md +++ b/notes/src/combinations.md @@ -68,3 +68,7 @@ void combineDFS(int n, int k, int begin, vector &path, } } ``` + +## [216. 组合总和 III](https://leetcode.cn/problems/combination-sum-iii/) + + diff --git a/src/s0216_combination_sum_iii.cpp b/src/s0216_combination_sum_iii.cpp new file mode 100644 index 0000000..0142eda --- /dev/null +++ b/src/s0216_combination_sum_iii.cpp @@ -0,0 +1,27 @@ +#include "s0216_combination_sum_iii.hpp" + +void combinationSum3DFS(int k, int n, int begin, vector &path, int sum, + vector> &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> S0216::combinationSum3(int k, int n) { + vector path{}; + vector> result; + combinationSum3DFS(k, n, 1, path, 0, result); + return result; +}