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 = A, return 3 because 12 = 4 + 4 + 4; given n =
Return 2 because 13 = 4 + 9.
Title translation: Give a positive integer n, to ask for at least how many full squares (e.g. 1,4,9,16 ... Added to get N.
For example, given n = 12, return 3, because 12 = 4 + 4 + 4. Given n = 13, return 2, because 13 = 4 + 9.
Specifically, we use an array to record the existing results and initialize them to positive infinity (Int_max). The outer loop variable i from 0 to N,
The inner loop variable J, on the basis of I, plus the total squared of each integer, exceeds N's count. So i + j*j this number takes
The minimum number of full squares is the current value in the array, and the value of the I position plus one, the smaller number between the two.
If the current value is small, it means that we have found the exact number of squares it needs (initially positive infinity). Otherwise, say
On the basis of I plus J squared to meet the conditions, the total number of squares required is the number I need plus one.
Importjava.util.Arrays;classSolution { Public intNumsquares (intN) {int[] DP =New int[n + 1]; Arrays.fill (DP, integer.max_value); dp[0] = 0; for(inti = 0; I <= N; i++) { for(intj = 1; i + J * J <= N; J + +) {Dp[i+ J * j] = Math.min (Dp[i + J * j], Dp[i] + 1); } } returnDp[n]; } Public Static voidMain (string[] args) {solution S=Newsolution (); intn = s.numsquares (8); SYSTEM.OUT.PRINTLN (n); }};
Leetcode Perfect Squares