Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...
) which sum to n.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
算法一, 动态规划
从1到n逐个计算。
应用递推式:
dp[i] = min(dp[i], 1+dp[i-j*j]);
即一个数是由 一个平方 + 另一个数 构成。 number1 = square + number2
而number2 结果已经计算过了。
在leetcode上实际执行时间为452ms。
class Solution {
public:
int numSquares(int n) {
vector<int> dp(n+1, INT_MAX);
dp[0] = 0;
for (int i=1; i<=n; i++) {
const int up = sqrt(i);
for (int j=1; j<=up; j++) {
dp[i] = min(dp[i], 1+dp[i-j*j]);
}
}
return dp[n];
}
};
算法二,BFS
基本模型,仍是 number1 = square + number2
即,number1, number2当作节点,而他们之间的边,则是一个 平方。
即一个数,加上一个 平方, 从而得到另一个数。
从根结点整数0从发,进行广度优先搜索,直到节点n为止。
即,
节点0加上一系列平方,得到一下层次的各个结点。
而对下一层次的结点,重复进行上面的步骤。
此处的visited数组很重要,否则会出现内存不足。
因为实际上这是一个图,而不是单纯的树。
在leetcode上实际执行时间为164ms。
class Solution {
public:
int numSquares(int n) {
const int up = sqrt(n);
vector<int> square(up);
for (int i=1; i<=up; i++)
square[i-1] = i*i;
vector<bool> visited(n+1, false);
queue<int> q;
q.push(0);
int level = 0;
while (!q.empty()) {
++level;
int size = q.size();
while (size--) {
auto node = q.front();
q.pop();
for (auto s: square) {
const auto child = s+node;
if (child == n)
return level;
else if (child < n && !visited[child]) {
q.push(child);
visited[child] = true;
}
else if (child > n)
break;
}
}
}
return level;
}
};
算法三,DFS
模型同上,进行深度优先搜索。
从n从发,减去一个平方,即得到下一层的一个节点。 直到找到节点0为止。
遍历所有路径,记录下最短的路径数。
1. 遍历时,使用变量level,限制递归的深度。以节省时间。
2. 先减去较大的平方,再减去较小的平方。 这样,当搜索到节点0时,所用的步数(即深度),不会特别大。从而用此深度,限制后续的搜索深度。
因为我们要找的是最短路径。
反之如果从1个平方开始递减的话,会出现大量的无用搜索。比如每次只减掉1,搜索n,将第一次会达到n层。
在leetcode上,实际执行时间为212ms。
class Solution {
public:
int numSquares(int n) {
vector<int> nums(n+1);
return helper(n, nums, n);
}
int helper(int n, vector<int>& nums, int level) {
if (!n)
return 0;
if (nums[n])
return nums[n];
if (!level)
return -1;
--level;
const int up = sqrt(n);
int ans = n;
int res = n;
for (int i=up; i>=1 && res; i--) {
res = helper(n-i*i, nums, min(ans, level));
if (res >= 0)
ans = min(ans, res);
}
nums[n] = ans + 1;
return nums[n];
}
};
将此写法也贴在leetcode中的一个answer中了,不知道会收获赞不。
https://leetcode.com/discuss/58056/summary-of-different-solutions-bfs-static-and-mathematics
算法四,数学公式
此此略去。难点是要懂得数学Lagrange's Four Square theorem。
代码上倒是没有什么复杂的。