Updated on February 19, 2019
Problem
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Examples:
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
Input
n
- integer
Approach
The brute force approach is to recursively use each perfect square number () and find a combination such that it gives us the least numbers to sum. The time complexity here is exponential.
The recursion is based off of the following recurrence relation:
One optimization is to cache results, using a hash table, and recursively iterate from the smallest perfect square to the biggest perfect square. At each total
, cache it into the hash map if it does not exist in the hash map; otherwise, read off of the cache to save some performance.
A better optimization than the former is to use dynamic programming -- that is, a bottom-up solution. In this optimization, instead of opting for recursion, we use a 2D array to pre-compute values, and use the recurrence relation formula above as the basis to populate the entire 2D array.
Solution
Note: We can improve this DP solution even further. Could you think of how?
Solution #2
This variation reduces space complexity by only using a 1D array, and improves time complexity by only taking advantage of square roots.