Skip to content

Commit 0fd9f64

Browse files
author
chen-shiwei
committed
feat: [dp]
1 parent 1b9fa41 commit 0fd9f64

File tree

4 files changed

+86
-0
lines changed

4 files changed

+86
-0
lines changed

leetcode/70.爬楼梯/climbStairs.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package _70_爬楼梯
2+
3+
func climbStairs(n int) int {
4+
if n < 3 {
5+
return n
6+
}
7+
var dp = make([]int, n+1)
8+
dp[1] = 1
9+
dp[2] = 2
10+
11+
for i := 3; i <= n; i++ {
12+
dp[i] = dp[i-1] + dp[i-2]
13+
}
14+
return dp[n]
15+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package _70_爬楼梯
2+
3+
import "testing"
4+
5+
func Test_climbStairs(t *testing.T) {
6+
type args struct {
7+
n int
8+
}
9+
tests := []struct {
10+
name string
11+
args args
12+
want int
13+
}{
14+
{name: ``, args: args{n: 3}, want: 3},
15+
}
16+
for _, tt := range tests {
17+
t.Run(tt.name, func(t *testing.T) {
18+
if got := climbStairs(tt.args.n); got != tt.want {
19+
t.Errorf("climbStairs() = %v, want %v", got, tt.want)
20+
}
21+
})
22+
}
23+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package _746_使用最小花费爬楼梯
2+
3+
func minCostClimbingStairs(cost []int) int {
4+
var (
5+
l = len(cost)
6+
dp = make([]int, l)
7+
)
8+
9+
dp[0] = cost[0]
10+
dp[1] = cost[1]
11+
for i := 2; i < l; i++ {
12+
dp[i] = min(dp[i-1], dp[i-2]) + cost[i]
13+
}
14+
15+
return min(dp[l-1], dp[l-2])
16+
}
17+
18+
func min(a, b int) int {
19+
if a > b {
20+
return b
21+
22+
}
23+
return a
24+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package _746_使用最小花费爬楼梯
2+
3+
import "testing"
4+
5+
func Test_minCostClimbingStairs(t *testing.T) {
6+
type args struct {
7+
cost []int
8+
}
9+
tests := []struct {
10+
name string
11+
args args
12+
want int
13+
}{
14+
{name: `输入:cost = [10, 15, 20] 输出:15`, args: args{cost: []int{10, 15, 20}}, want: 15},
15+
{name: `输入:cost = [1,100,1,1,1,100,1,1,100,1] 输出:15`, args: args{cost: []int{1, 100, 1, 1, 1, 100, 1, 1, 100, 1}}, want: 6},
16+
}
17+
for _, tt := range tests {
18+
t.Run(tt.name, func(t *testing.T) {
19+
if got := minCostClimbingStairs(tt.args.cost); got != tt.want {
20+
t.Errorf("minCostClimbingStairs() = %v, want %v", got, tt.want)
21+
}
22+
})
23+
}
24+
}

0 commit comments

Comments
 (0)