完全平方數

先算小於N的完全平方數,再用這些數做廣度優先:

class Solution:
    def numSquares(self, n: int) -> int:
        
        if n == 0:
            return 0
        
        tempNum = []
        
        x = 1
        i = 1
        #計算小於n的完全平方數
        while x <= n:
            tempNum.append(x)
            i += 1
            x = pow(i, 2)
        
        from collections import deque
        stack = deque([[n, 0]])
        
        while stack:     #使用廣度優先算法遍歷每層
            num, level = stack.popleft()
            for i in tempNum:
                temp = num - i
                if temp > 0:
                    stack.append([temp, level + 1])
                elif temp == 0:
                    return level + 1

大神解法:

class Solution:
    # isSquare 爲新增
    def isSquare(self, n: int) -> bool:
        sq = int(n ** 0.5)
        return sq * sq == n  

    def numSquares(self, n: int) -> int:
        #######  參考題解 用數學方法  拉格朗日四平方和定理######
        ################# python 動態規劃超時  ##############
        if self.isSquare(n):
            return 1
        while n & 3 == 0:
            n >>= 2
        if n & 7 == 7:
            return 4    # 滿足 4^a (8b+7)   返回 4
        for i in range(1, int(n ** 0.5)+1):
            if self.isSquare(n - i*i):
                return 2
        return 3

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章