leetcode-279-完全平方数*

题目描述:

 方法一:动态规划

一:超时

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [float("inf")] * (n + 1)
        dp[0] = 0
        for i in range(1, n + 1):
            for j in range(1, int(i ** 0.5) + 1):
                dp[i] = min(dp[i], dp[i - j * j] + 1)
        return dp[n]

二:

class Solution:
    _dp = [0]
    def numSquares(self, n):
        dp = self._dp
        while len(dp) <= n:
            dp += min(dp[-i*i] for i in range(1, int(len(dp)**0.5+1))) + 1,
        return dp[n]

方法二;bfs

class Solution:
    def numSquares(self, n: int) -> int:
        from collections import deque
        if n == 1 or n == 0:return n
        if n ** 0.5 % 1 == 0:return 1
        condidates = set(i*i for i in range(1,int(n**0.5)+1))
        queue = deque([n])
        step = 0
        while queue:
            step += 1
            l = len(queue)
            for _ in range(l):
                cur = queue.pop()
                for x in condidates:
                    tmp = cur -x
                    if tmp in condidates:
                        return step + 1
                    if tmp > 0:
                        queue.appendleft(tmp)
        

方法三:拉格朗日四数平方和定理

class Solution:
    def numSquares(self, n: int) -> int:
        while n % 4 == 0:
            n /= 4
        if n % 8 == 7:
            return 4
        
        a = 0
        while a**2 <= n:
            b = int((n - a**2)**0.5)
            if a**2 + b**2 == n:
                return bool(a) + bool(b)
            a += 1
        
        return 3

猜你喜欢

转载自www.cnblogs.com/oldby/p/11743139.html