分割整数
2. 按平方数来分割整数
- Perfect Squares(Medium)
题目描述:For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
class Solution:
def numSquares(self, n: int) -> int:
dp = [float('inf')]*(n+1)
dp[0] = 0
for i in range(n+1):
j = 1
while j*j <= i:
dp[i] = min(dp[i], dp[i-j*j]+1)
j+=1
return dp[n]