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.

Solution in python:

class Solution:
    def numSquares(self, n: int) -> int:
        k = [i**2 for i in range(1,int(n**0.5)+1)]
        dp = [n for i in range(n+1)]
        dp[0] = 0
        for i in range(1, n+1):
            j = 0
            while j < len(k) and k[j] <= i:
                temp = dp[i-k[j]] + 1
                if temp < dp[i]:
                    dp[i] = temp
                j += 1
        return dp[n]

Complexity analysis:

  • Time complexity: O(n\sqrt n)
  • Space complexity: O(n)
最后修改日期: 2020年9月15日

留言

撰写回覆或留言

发布留言必须填写的电子邮件地址不会公开。