文章 224
评论 6
浏览 200766
Dynamic Programming - 279. Perfect Squares

Dynamic Programming - 279. Perfect Squares

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.

Example 1:

Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

思路:

题目意思是求能用最少的完全平方表示一个数,有一个四平方和定理,可以在O(n)内解决问题,但是这里选择用动态规划来做,子问题就是一个数是由另一个数加上一个平方数,也就是比如A = B + x^2, 而B由是子问题求解,这样的话,能表示A的最少组合就是B最少组合加一,所以动态转移方程就是:dp[i] = min{dp[ i - j*j] + 1}, (j*j <= i),初始条件是dp[0] = 0, 因为0不能由状态方程求出。求解顺序很明显是从小到大。

代码:

go:

func numSquares(n int) int {
    dp := make([]int, n+1)
    for i := 0; i < n+1; i++ {
        dp[i] = math.MaxInt32
    }
    
    dp[0] = 0;
    for i := 1; i <= n; i++ {
        // dp[n] = min(dp[n-x^2] + 1) for all x
        for j := 1; j * j <= i; j++ {
            dp[i] = min(dp[i], dp[i- j*j] + 1)
        }
    }

    return dp[n]
}

func min(i, j int) int {
    if i < j {
        return i
    }
    return j
}

标题:Dynamic Programming - 279. Perfect Squares
作者:michael
地址:https://www.bitbo-liuyang.com/articles/2019/08/01/1564673300571.html

Nothing just happens, it's all part of a plan.

取消