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
3
Input: n = 12
Output: 3
Explanation: 12 = 4 + 4 + 4.

Example 2:

1
2
3
Input: 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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int numSquares(int n) {
if(n <=0) return 0;
vector<int> dp(n+1, INT_MAX);

dp[0] = 0;
for(int i= 0; i*i<=n; ++i) //pre-process, setup all the square number
dp[i*i] = 1;

for(int i= 1; i<= n; ++i){ //pick first number i
for(int j=1; i+j*j<=n; ++j){ //pick another number j*j
dp[i+j*j] = min(dp[i]+1, dp[i+j*j]);
}
}
return dp[n];
}
};

time complexity: $O(n)$
space complexity: $O(n)$
reference:
https://goo.gl/4R5avB