【題目描述】bash
【方法一:動態規劃】自底向上填充dp,思路沒問題,可是提交超時。app
def numSquares(self, n: int) -> int:
dp=[i for i in range(n+1)]
for i in range(4,n+1):
for j in range(int(n**0.5),1,-1):
if i>=j**2:
dp[i]=min(dp[i],dp[i-j*j]+1)
return dp[n]
複製代碼
【方法2:BFS】ui
至關於從根節點0,開始向下逐層延伸,每層可加的元素是1的平方到int(n**0.5)的平方,對於每一個節點均如此。spa
from collections import deque
class Solution:
def numSquares(self, n):
selected=[i**2 for i in range(1,int(n**0.5)+1)]
visited = set()
queue=deque([(0,0)])
while(queue):
current,height=queue.popleft()
for i in selected:
sum_= current+i
if sum_==n:
return height+1
if sum_<n and sum_ not in visited:
visited.add(sum_)
queue.append((sum_,height+1))
複製代碼