-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathnumSquares.go
More file actions
52 lines (44 loc) · 870 Bytes
/
Copy pathnumSquares.go
File metadata and controls
52 lines (44 loc) · 870 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* https://leetcode.com/problems/perfect-squares/description/
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, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
*/
package lmath
/*
func numSquares(n int) int {
dp := make([]int, n+1)
for i := 1; i*i <= n; i++ {
dp[i*i] = 1
}
for i := 1; i <= n; i++ {
for j := 1; i+j*j <= n; j++ {
if dp[i+j*j] == 0 || dp[i+j*j] > dp[i]+1 {
dp[i+j*j] = dp[i] + 1
}
}
}
return dp[n]
}
*/
import "math"
func numSquares(n int) int {
for n%4 == 0 {
n /= 4
}
if n%8 == 7 {
return 4
}
for i := 0; i*i <= n; i++ {
j := int(math.Sqrt(float64(n - i*i)))
if i*i+j*j == n {
res := 0
if i > 0 {
res++
}
if j > 0 {
res++
}
return res
}
}
return 3
}