python leetcode 279. Perfect Squares

四平方和定理

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        import math
        while n%4==0:
            n=n//4
        if n % 8 == 7:
            return 4 
        for i in range(int(math.sqrt(n)),0,-1):
            b = n - i*i
            if b ==0:
                return 1 
            for j in range(int(math.sqrt(b)),0,-1):
                c = b - j*j
                if c ==0:
                    return 2 
        return 3

猜你喜欢

转载自blog.csdn.net/Neekity/article/details/85122373