原题链接:279. 完全平方数
solution:
动态规划:
class Solution {
public:
int numSquares(int n) {
vector dp(n + 1);
for(int i = 1;i <= n;i++) {
dp[i] = INT_MAX;
for(int j = 1;j <= i / j;j++) {
dp[i] = min(dp[i],dp[i - j * j] + 1);
}
}
return dp[n];
}
};
广度优先搜索:求最短路径
class Solution {
public:
int numSquares(int n) {
vector dist(n + 1, 0x3f3f3f3f); //dist[n]数组表示到起点的距离
queue que;
dist[0] = 0;
que.push(0);
while(!que.empty()) {
auto t = que.front();
que.pop();
if(t == n) return dist[n];
for(int i = 1;t + i * i <= n;i++) {
int j = t + i * i;
if(dist[j] > dist[t] + 1) {
dist[j] = dist[t] + 1;
que.push(j);
}
}
}
return 0;
}
};



