Leetcode练习:完全平方数,python实现

给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。

示例 1:

输入: n = 12
输出: 3 
解释: 12 = 4 + 4 + 4.
示例 2:

输入: n = 13
输出: 2
解释: 13 = 4 + 9.

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/perfect-squares
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

我的思路:从1开始对1到n每个数建立 数->组成该数所需要的最小的完全平方数个数,比如 1->1,2->2, 3-> 3, 4->1...建立一个新的数的映射时需要用到之前的数据,具体方法为:

建立空数组square_list = []

i从1遍历到n。

如果i为完全平方数,在数组中添加1;

否则,初始化count = i,遍历数组中的1到int(i / 2)的元素,计算square_list[j] + square_list[i - j],如果该值小于count,则更新count为该值。

返回square_list[n]。

 

成绩为:

执行用时 :3636 ms, 在所有 Python 提交中击败了61.86%的用户

内存消耗 :12.1 MB, 在所有 Python 提交中击败了20.28%的用户

 

代码为:

def sqrt(n):
    i = 0
    while(i*i < n):
        i += 1
    return i

def isSquare(n):
    if sqrt(n) ** 2 == n:
        return True
    else:
        return False

square_list = []
for i in range(10000):
    if i == 0:
        square_list.append(0)
    elif isSquare(i):
        square_list.append(1)
    else:
        count = i
        for j in range(1, int(i/2)+1):
            if square_list[j] + square_list[i - j] < count:
                count = square_list[j] + square_list[i - j]
        square_list.append(count)

class Solution(object):
    def sqrt(self, n):
        i = 0
        while(i*i < n):
            i += 1
        return i

    def isSquare(self, n):
        if self.sqrt(n) ** 2 == n:
            return True
        else:
            return False

    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        """
        square_list = []
        for i in range(n+1):
            if i == 0:
                square_list.append(0)
            elif self.isSquare(i):
                square_list.append(1)
            else:
                count = i
                for j in range(1, int(i/2)+1):
                    if square_list[j] + square_list[i - j] < count:
                        count = square_list[j] + square_list[i - j]
                square_list.append(count)
        return square_list[-1]
        """
        return square_list[n]

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值