Overview
This problem is functionally identical to the "Coin Change" problem. In this case, the "coins" are dynamically generated perfect squares (1, 4, 9, 16...).
Loading...
Loading Curriculum...
Loading Subject...
Loading Topic...
Loading Lesson...
Loading Lab...
Given an integer n, return the least number of perfect square numbers that sum to n.
This problem is functionally identical to the "Coin Change" problem. In this case, the "coins" are dynamically generated perfect squares (1, 4, 9, 16...).
`dp[i]` stores the minimum number of squares needed to sum to `i`. We initialize the array with `Infinity` because we want to find the minimum.
For a target `i`, we test subtracting all perfect squares `j * j` that are less than or equal to `i`.
While DP solves this elegantly in O(N√N), Legendre's 3-Square Theorem can actually solve this in O(√N) time mathematically!