Skip to content

Latest commit

 

History

History
36 lines (30 loc) · 847 Bytes

279. 完全平方数-Medium.md

File metadata and controls

36 lines (30 loc) · 847 Bytes

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

示例 1:

输入: n = 12
输出: 3 
解释: 12 = 4 + 4 + 4.

示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.

Solution

  • 时间复杂度:$O(n\sqrt{n})$
  • 空间复杂度:$O(n)$
class Solution:
    def numSquares(self, n: int) -> int:
        squares = [i**2 for i in range(1, int(sqrt(n))+1)]

        dp = [float('inf') for i in range(n+1)]
        dp[0] = 0

        for i in range(n+1):
            for s in squares:
                if s > i:
                    break
                dp[i] = min(dp[i], dp[i-s]+1)
        
        return dp[-1]