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, givenN=12, return3Because12 = 4 + 4 + 4; GivenN=13, return2Because13 = 4 + 9.
Credits:
Special thanks to @jianchao. Li.fighter for adding the problem and creating all test cases.
Subscribe to see which companies asked this question.
Given a positive integer, the positive integer can be decomposed into the number of full squares.
For example, given n = A, return 3 because 12 = 4 + 4 + 4; Given n = 13, return 2 because = 4 + 9.
Adopt the idea of dynamic programming.
If n is the total square number, then f[n]=1;
otherwise f (n) = min{f (k) +f (n-k)},1<=K<=N/2
/** * Given a positive integer, the positive integer can be decomposed into the number of full squares. * For example, given n = A, return 3 because 12 = 4 + 4 + 4; Given n = 13, return 2 because = 4 + 9. * Adopt the idea of dynamic programming. * If n is the total square number, then f[n]=1; * otherwise f (n) = min{f (k) +f (n-k)},1<=K<=N/2 * @date 20160510 * @param n * @return */public int numsquares (int n) {if (n = = 1) {return 1;} int f[] = new Int[n+1];//f[i] indicates the exact square number of the corresponding condition that corresponds to a given i. f[1]=1;for (int i=2;i<=n;i++) {/* first determines whether a full square number */double y = math.sqrt (i), if (Y-(int) y = = 0) {F[i] = 1;continue;} /* Not for full square number when */f[i] = f[1]+f[i-1];for (int k=2;k<=i/2;k++) {if (F[k]+f[i-k]<f[i]) {f[i] = f[k]+f[i-k];}}} return f[n]; }
124.Perfect Squares