Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Perfect squares #254

Merged
merged 2 commits into from
May 6, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions leetcode-cc/PerfectSquares.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#include <queue>
#include <unordered_set>

#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<int, int>({12, 13}, {3, 2}, [this](auto input) {
return this->numSquares(input);
});
};
int benchmark() const override { return 0; }

private:
int numSquares(int n) const {
queue<pair<int, int>> q = {};
unordered_set<int> 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;
}
};
6 changes: 6 additions & 0 deletions runtime-cc/src/registration.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -982,5 +983,10 @@ const int registerAll(std::shared_ptr<Container> handle) {
return std::make_shared<SProductOfArrayExceptSelf>();
});

handle->registerProblem(
[]() -> ArcProblem { return std::make_shared<PPerfectSquares>(); });
handle->registerSolution(
[]() -> ArcSolution { return std::make_shared<SPerfectSquares>(); });

return 0;
}
Loading