279. Perfect Squares
Problem description:
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, …) which sum to n.
Example 1:1
2
3Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.
Example 2:1
2
3Input: n = 13
Output: 2
Explanation: 13 = 4 + 9.
Solution:
In this question, we can treat every number as combination of two numbers. In the following graph, we can see that we can use a number i
and a square number j*j
to get the final number i+j*j
.
1 | class Solution { |
time complexity: $O(n)$
space complexity: $O(n)$
reference:
https://goo.gl/4R5avB