四平方数定理:(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