四平方數定理:(theorem on the sum of foursquares)亦稱拉格朗日四平方數和定理。四平方數和問題是著名的數論問題.由拉格朗日(La-grange, J.-L.)最終解決,從而有上面的定理名字.該定理斷言:每個正整數均可表為四個整數的平方和(其中有些整數可以為零)。
推論:滿足四數平方和定理的數n(四個整數的情況),必定滿足 n=(4^ a) * (8b+7)
class Solution: def numSquares(self, n): """ :type n: int :rtype: 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 (not not a) + (not not b) a += 1 return 3
深度優先遍歷(層級遍歷)
class Solution: def numSquares(self, n): """ :type n: int :rtype: int """ q = list() q.append([n, 0]) visited = [False for _ in range(n+1)] visited[n] = True while any(q): num, step = q.pop(0) i = 1 tNum = num - i**2 while tNum >= 0: if tNum == 0: return step + 1 if not visited[tNum]: q.append((tNum, step + 1)) visited[tNum] = True i += 1 tNum = num - i**2