Ai
1 Star 2 Fork 5

LilithSangreal/LeetCode-Solutions

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
perfect-squares.cpp 826 Bytes
一键复制 编辑 原始数据 按行查看 历史
kamyu 提交于 2016-03-19 12:09 +08:00 . Update perfect-squares.cpp
// Time: O(n * sqrt(n))
// Space: O(n)
class Solution {
public:
int numSquares(int n) {
static vector<int> num{0};
while (num.size() <= n) {
int squares = numeric_limits<int>::max();
for (int i = 1; i * i <= num.size(); ++i) {
squares = min(squares, num[num.size() - i * i] + 1);
}
num.emplace_back(squares);
}
return num[n];
}
};
// Time: O(n * sqrt(n))
// Space: O(n)
class Solution2 {
public:
int numSquares(int n) {
vector<int> num(n + 1, numeric_limits<int>::max());
num[0] = 0;
for (int i = 0; i <= n; ++i) {
for (int j = i - 1, k = 1; j >= 0; ++k, j = i - k * k) {
num[i] = min(num[i], num[j] + 1);
}
}
return num[n];
}
};
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/LilithSangreal/LeetCode-Solutions.git
git@gitee.com:LilithSangreal/LeetCode-Solutions.git
LilithSangreal
LeetCode-Solutions
LeetCode-Solutions
master

搜索帮助