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.
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
class Solution:
def numSquares(self, n: int) -> int:
if n <= 1:
return n
# Step 1: Generate all perfect squares less than or equal to n
squares = []
i = 1
while i * i <= n:
squares.append(i * i)
i += 1
# Step 2: Initialize BFS
def bfs():
q = deque([n])
steps = 0
while q:
steps += 1
for _ in range(len(q)):
curr = q.popleft()
for square in squares:
if curr == square: # Found a perfect square
return steps
if curr < square: # No need to consider larger squares
break
q.append(curr - square)
return steps
return bfs()
