规范格式

This commit is contained in:
YDZ
2020-08-07 15:50:06 +08:00
parent 854a339abc
commit 4e11f4028a
1438 changed files with 907 additions and 924 deletions

View File

@ -0,0 +1,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
}

View File

@ -0,0 +1,41 @@
package leetcode
import (
"fmt"
"testing"
)
type question120 struct {
para120
ans120
}
// para 是参数
// one 代表第一个参数
type para120 struct {
one [][]int
}
// ans 是答案
// one 代表第一个答案
type ans120 struct {
one int
}
func Test_Problem120(t *testing.T) {
qs := []question120{
question120{
para120{[][]int{[]int{2}, []int{3, 4}, []int{6, 5, 7}, []int{4, 1, 8, 3}}},
ans120{11},
},
}
fmt.Printf("------------------------Leetcode Problem 120------------------------\n")
for _, q := range qs {
_, p := q.ans120, q.para120
fmt.Printf("【input】:%v 【output】:%v\n", p, minimumTotal(p.one))
}
fmt.Printf("\n\n\n")
}

View File

@ -0,0 +1,32 @@
# [120. Triangle](https://leetcode.com/problems/triangle/)
## 题目
Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
For example, given the following triangle
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
The minimum path sum from top to bottom is `11` (i.e., **2** + **3** + **5** + **1** = 11).
**Note:**
Bonus point if you are able to do this using only *O*(*n*) extra space, where *n* is the total number of rows in the triangle.
## 题目大意
给定一个三角形,找出自顶向下的最小路径和。每一步只能移动到下一行中相邻的结点上。
## 解题思路
- 求出从三角形顶端到底端的最小和。要求最好用 O(n) 的时间复杂度。
- 这一题最优解是不用辅助空间,直接从下层往上层推。普通解法是用二维数组 DP稍微优化的解法是一维数组 DP。解法如下