From 3e3c00b201802b0c8b39ddefabc05b9e089e4900 Mon Sep 17 00:00:00 2001 From: aucker Date: Sun, 25 Aug 2024 16:35:45 +0800 Subject: [PATCH] Aug25: DP and state problem [H] ... ... >_ --- daily/Aug25.cc | 53 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 daily/Aug25.cc diff --git a/daily/Aug25.cc b/daily/Aug25.cc new file mode 100644 index 0000000..614158e --- /dev/null +++ b/daily/Aug25.cc @@ -0,0 +1,53 @@ +#include +#include +using namespace std; + +class Solution { + public: + /** + * @brief LC698: partition to K equal sum subsets + * Time: O(N * 2^N), Space: O(2^N), DP + * + * @param nums + * @param k + * @return true + * @return false + */ + bool canPartitionKSubsets(vector& nums, int k) { + int sum = 0; + for (int num : nums) { + sum += num; + } + if (sum % k != 0) { + return false; + } + int per = sum / k; + sort(nums.begin(), nums.end()); + if (nums.back() > per) { + return false; + } + int len = nums.size(); + vector dp(1 << len, true); + // function dfs = [&](int s, int p) -> bool { + function dfs = [&](int s, int p) -> bool { + if (s == 0) return true; + + if (!dp[s]) return dp[s]; + + dp[s] = false; + for (int i = 0; i < len; i++) { + if (nums[i] + p > per) { + break; + } + if ((s >> i) & 1) { + if (dfs(s ^ (1 << i), (p + nums[i]) % per)) { + return true; + } + } + } + return false; + }; + + return dfs((1 << len) - 1, 0); + } +};