Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
method 1 BFS
本题是标准的BFS模板,当想记录BFS每层的宽度,可以进行两层遍历,第一层条件为队列非空,第二层条件为队列的size
int numSquares1(int n) {
vector<int> squares;
for (int i = 1; i * i <= n; i++)
squares.push_back(i * i);
int cnt = 0;
queue<int> q;
q.push(n);
while (!q.empty()){
int sz = q.size();
while (sz-- > 0)
{
int p = q.front(); q.pop();
for (int i = squares.size() - 1; i >= 0; i--){
if (p < squares[i]) continue;
int tmp = p - squares[i];
if (tmp == 0) return cnt + 1;
q.push(tmp);
}
}
cnt++;
}
return cnt;
}
method 2
使用动态规划节省运算量
状态转移方程为dp[i] = min(dp[i], dp[i - squares[j]] + 1);
int numSquares(int n) {
vector<int> squares;
for (int i = 1; i * i <= n; i++)
squares.push_back(i * i);
vector<int> dp(n + 1, n);
dp[0] = 0;
dp[1] = 1;
for (int i = 2; i <= n; i++){
for (int j = 0; j < squares.size(); j++)
{
if (i - squares[j] >= 0)
dp[i] = min(dp[i], dp[i - squares[j]] + 1);
}
}
return dp[n];
}
summary
- BFS标准模板,并且可以记录每层的宽度