diff --git a/CMakeLists.txt b/CMakeLists.txt index 1e8c3870..3729956a 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -82,6 +82,7 @@ add_task(binary-tree-preorder-traversal) add_task(binary-tree-right-side-view) add_task(binary-tree-tilt) add_task(binary-tree-zigzag-level-order-traversal) +add_task(binary-trees-with-factors) add_task(binary-watch) add_task(bitwise-and-of-numbers-range) add_task(bitwise-xor-of-all-pairings) diff --git a/solutions/binary-trees-with-factors/CMakeLists.txt b/solutions/binary-trees-with-factors/CMakeLists.txt new file mode 100644 index 00000000..bad688f4 --- /dev/null +++ b/solutions/binary-trees-with-factors/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_binary_trees_with_factors test.cpp) diff --git a/solutions/binary-trees-with-factors/solution.hpp b/solutions/binary-trees-with-factors/solution.hpp new file mode 100644 index 00000000..e8d70590 --- /dev/null +++ b/solutions/binary-trees-with-factors/solution.hpp @@ -0,0 +1,39 @@ +#pragma once + +#include +#include +#include +#include + +class Solution { +public: + static constexpr int kMod = 1e9 + 7; + + static int numFactoredBinaryTrees(std::vector arr) { + std::sort(arr.begin(), arr.end()); + + std::unordered_map indexes; + for (int i = 0; i < std::ssize(arr); ++i) { + indexes[arr[i]] = i; + } + + std::vector dp(arr.size(), 1); + for (int i = 1; i < std::ssize(arr); ++i) { + for (int j = 0; j < i; ++j) { + if (arr[j] > std::sqrt(arr[i])) { + break; + } + if (arr[i] % arr[j] != 0) { + continue; + } + if (auto it = indexes.find(arr[i] / arr[j]); it != indexes.end()) { + const int k = it->second; + dp[i] += (k == j ? 1 : 2) * dp[j] * dp[k]; + dp[i] %= kMod; + } + } + } + + return std::accumulate(dp.begin(), dp.end(), 0LL) % kMod; + } +}; diff --git a/solutions/binary-trees-with-factors/test.cpp b/solutions/binary-trees-with-factors/test.cpp new file mode 100644 index 00000000..2e51294c --- /dev/null +++ b/solutions/binary-trees-with-factors/test.cpp @@ -0,0 +1,26 @@ +#include + +#include + +TEST_CASE("Simple") { + struct TestCase { + std::vector arr; + int expected; + }; + + std::vector test_cases{ + { + .arr{2, 4, 5, 10}, + .expected = 7, + }, + { + .arr{2, 4}, + .expected = 3, + }, + }; + + for (const auto &[arr, expected] : test_cases) { + const auto actual = Solution::numFactoredBinaryTrees(arr); + REQUIRE(expected == actual); + } +}