Let dp[i] be the minimum number of perfect squares that sum to i. Base case: dp[0]=0 (you need zero squares to make zero).
For each i from 1 to n, try all perfect squares k2≤i. Compute dp[i]=min(dp[i],dp[i−k2]+1).
This says: to make i, take a perfect square k2 and add it to the optimal solution for i−k2. The answer is dp[n].