Title Link: https://leetcode.com/problems/perfect-squares/
Topic:
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
, return3
Because12 = 4 + 4 + 4
; given n =13
, return2
Because13 = 4 + 9
.
Ideas:
N=m^2+s
m= (int) math.sqrt (n) takes the entire table down to the maximum possible total number of squares c[i] represents the recursive formula for the minimum number of complete squares that comprise I:
C[i] =1+c[s] Consider 12=3^2+3 c[12]=1+c[3]=1+3=4, but 12=4+4+4 is c[12]=3
So not m for the maximum square number will be able to get c[i], need to traverse all j<m n=j^2+k min (1+c[k])
Algorithm:
public int numsquares (int n) { int c[] = new Int[n + 1]; for (int i = 1; I <= n; i++) { int tmp = (int) math.sqrt (i); C[i] = c[i-tmp * TMP] + 1; for (int j = tmp-1; J >= 1; j--) { tmp = J * J; C[i] = Math.min (c[i-tmp] + 1, c[i]); } } return c[n]; }
"Leetcode" Perfect Squares