leetcode:Perfect Squares -----BFS

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.

BFS解法:

思路:

 

 重点是用state记录结果在哪一层,层数就是所求结果。

class Solution {
public:
    int numSquares(int n) {
        int leng = sqrt(n);
        vector<int> square;
        vector<int> state(n+1,0);
        queue<int> q;
        for(int i=1;i<=leng;i++){
            square.push_back(i*i);
        }
        q.push(0);
        while(!q.empty()){
            int now =  q.front();
            q.pop();
            for(int k:square){
                if(now+k<=n && state[now+k]==0){
                    q.push(now+k);
                    state[now+k]=state[now]+1;
                }
            }
        }
        return state[n];
    }
};

猜你喜欢

转载自blog.csdn.net/qq_36428318/article/details/85916639