Math Fundamentals18 sections · 814 units
Open in Course

Perfect Squares - DP Insight

Building from smaller values

Let dp[i]dp[i] be the minimum number of perfect squares that sum to ii. Base case: dp[0]=0dp[0] = 0 (you need zero squares to make zero).

For each ii from 11 to nn, try all perfect squares k2ik^2 \leq i. Compute dp[i]=min(dp[i],dp[ik2]+1)dp[i] = \min(dp[i], dp[i - k^2] + 1).

This says: to make ii, take a perfect square k2k^2 and add it to the optimal solution for ik2i - k^2. The answer is dp[n]dp[n].