Problem: Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n.
Example:
Input: n = 34
Output: 2
Explanation: 34 = 25 + 9.
Approach: We can solve it using recursive approach. The recursion will be something like:
- result = n
- WHILE a * a <= n
- result = Min (result, 1 + Fn(n - a*a))
- Table[0...3] = {0...3}
- Table[i] = i
- Foreach j where j = 1 to j * j <= i
- Table[i] = Min(Table[i], 1 + Table[i - j *j])
That's all!
Implementation in C#:
public static int MinNumPerfectSquares(int n)
{
if (n <= 3)
{
return n;
}
if (IsPerfectSquare(n))
{
return 1;
}
int[] table = new int [n + 1];
for (int i = 0; i <= 3; ++i)
{
table[i] = i;
}
for (int i = 4; i <= n; ++i)
{
table[i] = i;
for (int j = 1; j * j <= i; ++j)
{
table[i] = Math.Min(table[i], 1 + table[i - j * j]);
}
}
return table[n];
}
Complexity: O(nlogn)
No comments:
Post a Comment