From 4c03b8e53355d8de838792a881094a8c623cafa9 Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Tue, 10 May 2022 19:52:02 +0800 Subject: [PATCH] add: 220510 [cpp] --- cpp/2205/220510.cpp | 62 +++++++++++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220510.cpp diff --git a/cpp/2205/220510.cpp b/cpp/2205/220510.cpp new file mode 100644 index 0000000..e2d2948 --- /dev/null +++ b/cpp/2205/220510.cpp @@ -0,0 +1,62 @@ +#include +#include +#include + +/** + * 216. Combination Sum III + * Find all valid combinations of k numbers that sum up to n such that the following conditions are true: + * + * Only numbers 1 through 9 are used. + * Each number is used at most once. + * Return a list of all possible valid combinations. The list must not contain the same combination twice, and the combinations may be returned in any order. + */ + +class Solution { +public: + static std::vector> combinationSum3(int k, int n) { + int current = 0; + std::vector work; + std::vector> ret; + work.reserve(k); + + std::function dfs = [&](int rem, int begin) { + if (rem <= 1) { + if (n - current > work.back() && n - current < 10) { + ret.push_back(work); + ret.back().push_back(n - current); + } + return; + } + + for (int i = begin; i <= 9; current -= i++ /* On Exit */) { + // On Entry + current += i; + + // rem is at least 2. + if (current + (rem - 1) * (i + 1) + (rem - 1) * (rem - 2) / 2 > n) { + current -= i; + break; + } + + work.push_back(i); + dfs(rem - 1, i + 1); + work.pop_back(); + } + }; + + dfs(k, 1); + + return ret; + } +}; + +int main() { + auto r = Solution::combinationSum3(5, 30); + for (const auto& i : r) { + for (const auto& j : i) { + std::cout << j << ' '; + } + std::cout << std::endl; + } + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 364e3a4..edcb186 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220509.cpp) +ADD_EXECUTABLE(2205 220510.cpp)