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.
For example, given n = 12
, return 3
because 12 = 4 + 4 + 4
; given n = 13
, return 2
because 13 = 4 + 9
.
- n = a + b * b
- a:n之前的某个值
- n必定由一个值+完美平方数组成
- 这个值为子问题,也是最佳问题
int numSquares(int n) { //开辟n个大小的数组,初始化为0 int *result = calloc((n + 1), sizeof(int)); //填入平方的值 int sqrtn = sqrt(n); result[1] = 1; for (int i = 2; i <= n; i++){ int min = n; int j = 1; while(j * j <= i){ if (min > result[i - j*j] + 1) min = result[i - j*j] + 1; j++; } result[i] = min; } return result[n]; }