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

LeetCode:链接

使用动态规划,维护一个长度为n+1的数组,第i位存储和为i的最少整数个数。则f(i)只与i之前的数组有关。

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n == 0:
            return 0
        dp = [0x7fffffff] * (n + 1)
        dp[0] = 0
        dp[1] = 1
        for i in range(2, n+1):
            j = 1
            while j*j <= i:
                # j*j已经代表了一个整数 所以要+1
                dp[i] = min(dp[i], dp[i-j*j] + 1)
                j += 1
        return dp[n]

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84998885