码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode-279-完全平方数*

时间:2019-10-26 15:26:24      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:png   imp   http   date   src   append   div   float   step   

题目描述:

技术图片

 

 方法一:动态规划

一:超时

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

 

leetcode-279-完全平方数*

标签:png   imp   http   date   src   append   div   float   step   

原文地址:https://www.cnblogs.com/oldby/p/11743139.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!