leetcode perfect square --- 重点

https://leetcode.com/problems/perfect-squares/


understanding:


可以有数论,DP, BFS三种思路求解,

数论:推荐用这种方法


这个ref里面详细的讲了

http://www.cnblogs.com/grandyang/p/4800552.html




解法II:动态规划(Dynamic Programming)

时间复杂度:O(n * sqrt n)

初始化将dp数组置为无穷大;令dp[y * y] = 1,其中:y * y <= n。这里意思就是说本身就是平方和,那么当然结果是1

状态转移方程:

dp[x + y * y] = min(dp[x + y * y], dp[x] + 1)

其中:dp [i] 表示凑成i所需的平方和数字的最小个数,并且 x + y * y <= n



转移公式 就是 dp[n] = 1 + min([ dp[n - j**2] for j in xrange(1, int(n**0.5) + 1)]), 就是当前n对应的perfect square的数目减去一,即减去一个perfect square, 剩下的部分肯定也要是拥有最少perfect square的部分,并且这个要减去的perfect square,不能任意减,最多也就是减去自己的sqrt


这个版本leetcode 不让过,超时

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        if n<=0 : 
            return 0
        
        dp = [0]
        
        for i in xrange(1, n + 1):
            
            tmp = 1 + min([ dp[i - j ** 2] for j in xrange(1, int(i**0.5) + 1)])
            dp.append(tmp)
        return dp[-1]


不过思想对了就行

参考代码:http://bookshadow.com/weblog/2015/09/09/leetcode-perfect-squares/

http://traceformula.blogspot.hk/2015/09/perfect-squares-leetcode.html


BFS:


广搜:

http://traceformula.blogspot.hk/2015/09/perfect-squares-leetcode.html







评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值