From 61780faad2f964de8b53b1c8030db1e1e30d65ff Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Wed, 1 Jun 2022 15:38:29 +0800 Subject: [PATCH] add: 220601-CN [cpp] --- cpp/2206/220601-CN.cpp | 44 +++++++++++++++++++++++++++++++++++++++++ cpp/2206/CMakeLists.txt | 2 +- 2 files changed, 45 insertions(+), 1 deletion(-) create mode 100644 cpp/2206/220601-CN.cpp diff --git a/cpp/2206/220601-CN.cpp b/cpp/2206/220601-CN.cpp new file mode 100644 index 0000000..907d4bc --- /dev/null +++ b/cpp/2206/220601-CN.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +#include + +/** + * 473. Matchsticks to Square + * You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick. You want to use all the matchsticks to make one square. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time. + * Return true if you can make this square and false otherwise. + */ + +class Solution { +public: + static bool makesquare(std::vector& matchsticks) { + std::sort(matchsticks.begin(), matchsticks.end(), std::greater<>()); + int sum = std::accumulate(matchsticks.begin(), matchsticks.end(), 0); + if ((sum & 3) || (sum >> 2) < matchsticks.front()) + return false; + int length[4]{}, n = matchsticks.size(); + + std::function dfs = [&](int depth) { + if (depth >= n) { + return !std::any_of(length + 1, length + 4, [&](int x) { return x != length[0]; }); + } + bool ok = false; + for (int& i : length) { + i += matchsticks[depth]; + if (i <= (sum >> 2) && dfs(depth + 1)) + ok = true; + i -= matchsticks[depth]; + if (ok) break; + } + return ok; + }; + + return dfs(0); + } +}; + +int main() { + std::vector arg {3,3,3,3,4}; + Solution::makesquare(arg); + return 0; +} diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index 83f04b9..128c9a8 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220601.cpp) +ADD_EXECUTABLE(2206 220601-CN.cpp)