Created
June 30, 2020 08:17
-
-
Save alldroll/b811b6f4ac09474132add6620b2c1994 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| func numSquares(n int) int { | |
| // we are going to keep the minumum number of squares required to get the corresponding number | |
| // index here represents the desire number | |
| nums := make([]int, n + 1) | |
| // we calculate the minumum number of squares for each number from 1 to n | |
| for i := 1; i <= n; i++ { | |
| // as we have to get the minumum, at the first step we use INF as undefined number | |
| num := (1 << 31) - 1 | |
| // here we walk through the list of squares up to the current number | |
| for j := 1; j * j <= i; j++ { | |
| square := j * j | |
| // min_number = min(current_number - square + 1, min_number) | |
| num = min(num, nums[i - square] + 1) | |
| } | |
| nums[i] = num | |
| } | |
| return nums[n] | |
| } | |
| func min(a, b int) int { | |
| if a < b { | |
| return a | |
| } | |
| return b | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment