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 [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