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.
The simplest way to solve the problem is by trying all combinations. For a given number n, see if you can subtract a perfect square and solve the rest of the problem for n - perfect_square recursively.
n by i*i, where i goes from 1 to sqrt(n).n is 0, return 0 as we do not need any squares to sum up to 0.sqrt(n) branches.We can improve upon the recursive approach by storing results of subproblems (memoization). Use an array where dp[i] keeps track of the least number of perfect squares that sum up to i.
dp of size n + 1 where dp[0] = 0.n and compute dp[i] by adding a perfect square j*j.i, dp[i] equals the min of dp[i] and dp[i - j*j] + 1.sqrt(n).dp array.Lagrange's Four Square Theorem states that any natural number is the sum of four integer squares at most. Using some mathematical deductions, especially checking for perfect squares can make the solution optimal.
n is a perfect square.