Here's the dynamic programming solution:
function numSquares(n)
dp := array of size (n + 1) filled with infinity
dp[0] := 0
for i from 1 to n
j := 1
while j * j ≤ i
dp[i] := min(dp[i], dp[i - j * j] + 1)
j := j + 1
return dp[n]
You build up from to . For each , you try all perfect squares and take the minimum. The answer is .