天天看點

leetcode 279 : 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.

中文意思就是:給定了一個正整數n , 要求用最少個數的平方數相加的方法重構出來。比如 n=12 時,因為 12=4+4+4, 有三個數相加是以傳回 3, n=13 時, 13=4+9 , 傳回 2 。

思路解析: 這是一個動态規劃問題(dp),初始化時令dp[i * i] = 1,狀态轉移方程為dp[i + j * j] = min(dp[i] + 1, dp[i + j * j]);

class Solution {
public:
    int numSquares(int n) {
        vector<int> dp(n + , );
        for (int i = ; i * i <= n; i++)
        {
            dp[i * i] = ;
        }

        for (int i = ; i <= n; i++)
        {
            for (int j = ; i + j * j <= n; j++)
            {
                dp[i + j * j] = min(dp[i] + , dp[i + j * j]);
            }
        }

        return dp[n];
    }
};