LeetCode: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.

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

題目的意思即給定一個正整數,找出k個可以開方的整數,使這k個整數的和爲指定的正整數並且使k值最小,返回這個最小的k(以下把這個數成爲res).

解題分析:

可以使用動態規劃的思想來解決,使用一個數組cntPerfectSquares[i]來保存數i的res,狀態轉移方程爲:

cntPerfectSquares[i] = min(cntPerfectSquares[i], cntPerfectSquares[i – j*j] + 1),其中j*j < =i

則代碼如下:

class Solution 
{
public:
    int numSquares(int n) 
    {
        if (n <= 0)
        {
            return 0;
        }
        
        // cntPerfectSquares[i] = the least number of perfect square numbers 
        // which sum to i. Note that cntPerfectSquares[0] is 0.
        vector<int> cntPerfectSquares(n + 1, INT_MAX);
        cntPerfectSquares[0] = 0;
        for (int i = 1; i <= n; i++)
        {
            // For each i, it must be the sum of some number (i - j*j) and 
            // a perfect square number (j*j).
            for (int j = 1; j*j <= i; j++)
            {
                cntPerfectSquares[i] = 
                    min(cntPerfectSquares[i], cntPerfectSquares[i - j*j] + 1);
            }
        }
        
        return cntPerfectSquares.back();
    }
};
点赞