1 """ 2 Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. 3 Example 1: 4 Input: n = 12 5 Output: 3 6 Explanation: 12 = 4 + 4 + 4. 7 Example 2: 8 Input: n = 13 9 Output: 2 10 Explanation: 13 = 4 + 9. 11 """ 12 """ 13 dp[0] = 0 14 dp[1] = dp[0]+1 = 1 15 dp[2] = dp[1]+1 = 2 16 dp[3] = dp[2]+1 = 3 17 dp[4] = Min{ dp[4-1*1]+1, dp[4-2*2]+1 } 18 = Min{ dp[3]+1, dp[0]+1 } 19 = 1 20 dp[5] = Min{ dp[5-1*1]+1, dp[5-2*2]+1 } 21 = Min{ dp[4]+1, dp[1]+1 } 22 = 2 23 . 24 . 25 . 26 dp[13] = Min{ dp[13-1*1]+1, dp[13-2*2]+1, dp[13-3*3]+1 } 27 = Min{ dp[12]+1, dp[9]+1, dp[4]+1 } 28 = 2 29 . 30 . 31 . 32 dp[n] = Min{ dp[n - i*i] + 1 }, n - i*i >=0 && i >= 1 33 is DP [n] represents the number of least squares and the sum of n is (the request). 34 is DP all indices array has completely square numbers is a number (e.g. 1,4,9 ...) is set to 1, plus a layer traverse to find the smallest j combined length of the current i. 35 meaning that the dynamic equation: for each i, i is smaller than a full number of those in the square of the minimum number +1 is the desired, i.e. dp [i - j * j] + 1. 36 "" " 37 [ class Solution1: 38 is DEF numSquares (Self, n-): 39 DP = [a float ( ' INF ' )] * (n-+. 1 ) 40 I =. 1 41 is the while I * I <= n-: 42 is DP [ I * I]. 1 = 43 is I = +. 1 44 is for I in Range (. 1,. 1 n-+ ): 45 j = 1 46 while j*j <= i: 47 dp[i] = min(dp[i], dp[i-j*j]+1) 48 j += 1 49 return dp[n]