Problem 441
Perfect Squares
Medium · 20 pts · Math, Dynamic Programming, Breadth-First Search
Problem
Find the least number of perfect squares (1, 4, 9, 16, ...) that add up to N. The same square may be used more than once. For example, 12 = 4 + 4 + 4 needs three squares, and 13 = 4 + 9 needs two. A dynamic program where best[i] = 1 + min(best[i - s]) over squares s <= i solves it in O(N·sqrt(N)).
Input
A single integer N.
Output
Print the least number of perfect squares that add up to N.
Constraints
1 <= N <= 10000
Example input
12
Example output
3
Explanation
12 is not a square and is not a sum of two squares, but 12 = 4 + 4 + 4, so the answer is 3.