Leetcode Perfect Squares 拉格朗日四平方

231 篇文章 0 订阅
120 篇文章 1 订阅

Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.

Example 1:

Input: n = 12
Output: 3 
Explanation: 12 = 4 + 4 + 4.

Example 2:

Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.

-------------------------------------------------------------

BFS code is straightfoward...

朗格朗日四平方定理
每个正整数均可表示成不超过四个整数的平方之和

重要的推论

1. 数 n 如果只能表示成四个非零整数的平方和的充要条件是 4^a(8b+7),其中a>=0, b>=0
2. 如果 n%4==0,k=n/4,n 和 k 可由相同个数的整数表示

那么代码是:

class Solution:
    def is_square(self, n):
        num = math.floor(math.sqrt(n))
        return num*num == n

    def is_2_square(self, n):
        num = math.floor(math.sqrt(n//2))
        for i in range(1,num+1):
            if (self.is_square(n-i*i)):
                return True
        return False
    
    def numSquares(self, n):
        if (self.is_square(n)):
            return 1
        elif (self.is_2_square(n)):
            return 2
        while (n % 4 == 0):
            n = n//4
        if (n >= 7 and (n-7) % 8 == 0):
            return 4
        return 3

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值