LeetCodeDiary

A Diary for solving LeetCode problems

View on GitHub

279. 完全平方数

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

给你一个整数 n ,返回和为 n 的完全平方数的 最少数量

完全平方数 是一个整数,其值等于另一个整数的平方;换句话说,其值等于一个整数自乘的积。例如,14916 都是完全平方数,而 311 不是。

示例 1:

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

示例 2:

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

提示:

动态规划 中等 每日一题

背包问题的一种, 曾经做过的题。

题解

代码

1. 动态规划

class Solution:
    def numSquares(self, n: int) -> int:
        # dp[i] 表示凑成n的最少个数为dp[i]
        dp = [n+1] * (n+1)
        dp[0] = 0
        for i in range(1, n+1):
            for j in range(i*i, n+1):
                dp[j] = min(dp[j-i*i]+1, dp[j])
        return dp[-1]

2. 数学规律

class Solution:
    def isSquare(self, n: int) -> bool:
        sq = int(math.sqrt(n))
        return sq*sq == n

    def numSquares(self, n: int) -> int:
        # four-square and three-square theorems
        while (n & 3) == 0:
            n >>= 2      # reducing the 4^k factor from number
        if (n & 7) == 7: # mod 8
            return 4

        if self.isSquare(n):
            return 1
        # check if the number can be decomposed into sum of two squares
        for i in range(1, int(n**(0.5)) + 1):
            if self.isSquare(n - i*i):
                return 2
        # bottom case from the three-square theorem
        return 3