-
-
Notifications
You must be signed in to change notification settings - Fork 5.7k
/
120. Triangle.go
56 lines (52 loc) · 1.13 KB
/
120. Triangle.go
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
53
54
55
56
package leetcode
import (
"math"
)
// 解法一 倒序 DP,无辅助空间
func minimumTotal(triangle [][]int) int {
if triangle == nil {
return 0
}
for row := len(triangle) - 2; row >= 0; row-- {
for col := 0; col < len(triangle[row]); col++ {
triangle[row][col] += min(triangle[row+1][col], triangle[row+1][col+1])
}
}
return triangle[0][0]
}
func min(a int, b int) int {
if a > b {
return b
}
return a
}
// 解法二 正常 DP,空间复杂度 O(n)
func minimumTotal1(triangle [][]int) int {
if len(triangle) == 0 {
return 0
}
dp, minNum, index := make([]int, len(triangle[len(triangle)-1])), math.MaxInt64, 0
for ; index < len(triangle[0]); index++ {
dp[index] = triangle[0][index]
}
for i := 1; i < len(triangle); i++ {
for j := len(triangle[i]) - 1; j >= 0; j-- {
if j == 0 {
// 最左边
dp[j] += triangle[i][0]
} else if j == len(triangle[i])-1 {
// 最右边
dp[j] += dp[j-1] + triangle[i][j]
} else {
// 中间
dp[j] = min(dp[j-1]+triangle[i][j], dp[j]+triangle[i][j])
}
}
}
for i := 0; i < len(dp); i++ {
if dp[i] < minNum {
minNum = dp[i]
}
}
return minNum
}