perfect_nums = [i * i for i inrange(1, int(n**0.5)+1)]
[12] [11,8,9][[10,7,2], [7,4], [2]] ...
classSolution:defnumSquares(self,n:int) ->int: perfect_nums = [i **2for i inrange(1, int(n**0.5)+1)]@lru_cache(None)defdp(n):if n ==0:return0return1+min([dp(n-num) for num in perfect_nums if num <= n])returndp(n)
classSolution:defnumSquares(self,n:int) ->int: perfect_nums = [i * i for i inrange(1, int(n**0.5)+1)] queue =deque([n]) level =0while queue: level +=1 size =len(queue)for i inrange(size): node = queue.popleft()for child in perfect_nums:if child == node:return levelelif child > node:breakelse: queue.append(node - child)