leetcode [279] - Perfect Squares
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:
Input: n =12
Output: 3 Explanation:12 = 4 + 4 + 4.
Example 2:
Input: n =13
Output: 2
Explanation:13 = 4 + 9.
题目大意:
找到几个数的平方的和为n,输出满足条件的最小个数。
理 解:
组成n的多个数的组合情况有多种。对于n,从sqrt(n)及以下的数中找到满足条件的数。
使用动态规划的方法,从1-n由小到大构成所有最小数。对于数n,若使用了数i,则n的最小个数为NUM(n) = 1 + NUM(n-i*i);更新满足n的最小个数。
代 码 C++:
class Solution { public: int numSquares(int n) { int *arr = new int[n + 1]; if (n == 0)return 0; if (n > 0 && n < 4) return n; if (n == 4)return 1; arr[0] = 0; arr[1] = 1; arr[2] = 2; arr[3] = 3; arr[4] = 1; for (int i = 5;i <= n;++i) { int min = i,count; for (int j = sqrt(i);j > 0;j--) { if (i >= j * j) { i = i - j * j; count = arr[i] + 1; if (min > count) min = count; i = i + j * j; } } arr[i] = min; } return arr[n]; } };