题目描述
Given an integer n, return the least number of perfect square numbers that sum to n.
A perfect square is an integer that is the square of an integer; in other words, it is the product of some integer with itself. For example, 1, 4, 9, and 16 are perfect squares while 3 and 11 are not.
解题思路
典型的 dp 问题。首先看最优解的构造,另 dp[i] 表示和为i的最优解,那么 d p [ i ] = m i n k d p [ i − k ] + 1 , k ∈ S q u a r e dp[i] = min_kdp[i - k] + 1, k\in Square dp[i]=minkdp[i−k]+1,k∈Square 此算法的时间复杂度为 O ( n 3 2 ) O({n^\frac{3}{2}}) O(n23).
代码
class Solution:
def numSquares(self, n: int) -> int:
perfect_square = []
for i in range(101):
if i * i < 10000:
perfect_square.append(i * i)
dp = [10000] * (n + 1)
dp[1] = 1
for i in range(2, n + 1):
if i in perfect_square:
dp[i] = 1
continue
mn = 10000
for j in perfect_square:
if j < i:
if dp[i - j] < mn:
mn = dp[i - j]
else:
break
dp[i] = mn + 1
return dp[n]