Leetcode Perfect Square

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

For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.

这道题首先想到的算法是DP。每个perfect square number对应的解都是1。先生成一个n+1长的DP list。对于每个i,可以用dp[i] = min(dp[j] + dp[i-j], dp[i])来更新,这里j 是<= i 的一个perfect square number。但是DP的算法超时。

 class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
MAX = 2147483647
m = 1
perfect = [m]
while m**2 <= n:
perfect.append(m**2)
m += 1 dp = [MAX]*(n+1)
dp[0] = 1
for x in perfect:
dp[x] = 1 for i in range(2, n+1):
curP = [x for x in perfect if x <= i]
for j in curP:
dp[i] = min(dp[j] + dp[i-j], dp[i]) return dp[-1]

解法二: 来自 https://www.cnblogs.com/grandyang/p/4800552.html

任何一个正整数都可以写成最多4个数的平方和。然后又两条性质可以简化题目:

1. 4q 和 q 的答案一样,i.e. 3, 12。

2. 如果一个数除以8余7 <=> 答案是4。

 class Solution(object):
def numSquares(self, n):
"""
:type n: int
:rtype: int
"""
while n % 4 == 0:
n = n//4 if n % 8 == 7:
return 4 a = 0
while a**2 <= n:
b = int(math.sqrt(n - a**2))
if a**2 + b**2 == n:
if a>0 and b>0:
return 2
if a == 0 and b>0:
return 1
if a>0 and b==0:
return 1
a += 1
return 3
上一篇:将本地代码提交至gitHub


下一篇:C和指针 第十二章 结构体 整体赋值 error: expected expression