例題1
https://leetcode-cn.com/problems/perfect-squares/
描述
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.
解析
class Solution {
public:
unordered_set<int> sett;
int numSquares(int n) {
queue<int> q;
q.push(0);
int step=0;
while(!q.empty()){
step++;
int cnt=q.size();
while(cnt--){ //逐層入隊
int num=q.front();
q.pop();
for(int i=1;i*i<=n-num;i++){
int a=num+i*i;
if(a>n) break;
if(a==n) return step;
if(sett.count(a)==0){ //剪枝
q.push(a); //將平方數的和入隊以保存狀態
sett.insert(a);
}
}
}
}
return 0;
}
};