diff --git a/leetcode-cc/PerfectSquares.hpp b/leetcode-cc/PerfectSquares.hpp new file mode 100644 index 0000000..46a5af6 --- /dev/null +++ b/leetcode-cc/PerfectSquares.hpp @@ -0,0 +1,53 @@ +#include +#include + +#include "TestHelper.h" +#include "problem.h" +#include "solution.h" + +using namespace std; + +IMPLEMENT_PROBLEM_CLASS(PPerfectSquares, 279, DIFFI_MEDIUM, TOPIC_ALGORITHMS, + "Perfect Squares", + "Given an integer n, return the least number of " + "perfect square numbers that sum to n.", + {"Math"}); + +class SPerfectSquares : public ISolution { + public: + size_t problemId() const override { return 279; } + string name() const override { + return ("Solution for " + string("Perfect Squares")); + } + string location() const override { return __FILE_NAME__; } + int test() const override { + return testHelper({12, 13}, {3, 2}, [this](auto input) { + return this->numSquares(input); + }); + }; + int benchmark() const override { return 0; } + + private: + int numSquares(int n) const { + queue> q = {}; + unordered_set memo = {}; + + q.push({0, 0}); + + while (!q.empty()) { + auto [val, step] = q.front(); + q.pop(); + + if (val == n) return step; + + memo.insert({val, step}); + + for (int i = 1; i * i + val <= n; i++) { + auto nextVal = val + i * i; + if (!memo.contains(nextVal)) q.push({nextVal, step + 1}); + } + } + + return -1; + } +}; diff --git a/runtime-cc/src/registration.cc b/runtime-cc/src/registration.cc index 605e13a..062c930 100644 --- a/runtime-cc/src/registration.cc +++ b/runtime-cc/src/registration.cc @@ -94,6 +94,7 @@ #include "../leetcode-cc/PascalsTriangleII.hpp" #include "../leetcode-cc/PathSum.hpp" #include "../leetcode-cc/PathSumII.hpp" +#include "../leetcode-cc/PerfectSquares.hpp" #include "../leetcode-cc/PopulateNextRightPointers.hpp" #include "../leetcode-cc/ProductOfArrayExceptSelf.hpp" #include "../leetcode-cc/PseudoPalindromicPathsInBTree.hpp" @@ -982,5 +983,10 @@ const int registerAll(std::shared_ptr handle) { return std::make_shared(); }); + handle->registerProblem( + []() -> ArcProblem { return std::make_shared(); }); + handle->registerSolution( + []() -> ArcSolution { return std::make_shared(); }); + return 0; }