Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitab3bad6

Browse files
authored
Merge pull request6boris#129 from kylesliu/develop
update 198 Solution
2 parents01450bb +db7433e commitab3bad6

File tree

2 files changed

+40
-17
lines changed

2 files changed

+40
-17
lines changed

‎src/0198.House-Robber/Solution.go

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@ package Solution
22

33
//普通的动态规划
44
funcrob(nums []int)int {
5-
nLenghth:=len(nums)
5+
dp:=make([][2]int,len(nums)+1)
66

7-
dp:=make([][2]int,nLenghth+1)
8-
fori:=1;i<=nLenghth;i++ {
9-
dp[i][0]=Max(dp[i-1][0],dp[i-1][1])
7+
fori:=1;i<=len(nums);i++ {
8+
dp[i][0]=max(dp[i-1][0],dp[i-1][1])
109
dp[i][1]=nums[i-1]+dp[i-1][0]
1110
}
1211
//fmt.Println(dp)
13-
returnMax(dp[nLenghth][0],dp[nLenghth][1])
12+
returnmax(dp[len(nums)][0],dp[len(nums)][1])
1413
}
1514

1615
//优化空间
@@ -19,26 +18,27 @@ func rob2(nums []int) int {
1918

2019
for_,v:=rangenums {
2120
tmp:=prevNo
22-
prevNo=Max(prevNo,prevYes)
21+
prevNo=max(prevNo,prevYes)
2322
prevYes=v+tmp
2423
}
25-
returnMax(prevNo,prevYes)
24+
returnmax(prevNo,prevYes)
2625
}
2726

28-
funcMax(x,yint)int {
29-
ifx>y {
30-
returnx
31-
}
32-
returny
33-
}
3427
funcrob3(nums []int)int {
3528
robEven,robOdd:=0,0
3629
fori:=0;i<len(nums);i++ {
37-
ifi%2==0 {
38-
robEven=Max(robEven+nums[i],robOdd)
30+
ifi%2==0 {
31+
robEven=max(robEven+nums[i],robOdd)
3932
}else {
40-
robOdd=Max(robEven,nums[i]+robOdd)
33+
robOdd=max(robEven,nums[i]+robOdd)
4134
}
4235
}
43-
returnMax(robEven,robOdd)
36+
returnmax(robEven,robOdd)
37+
}
38+
39+
funcmax(x,yint)int {
40+
ifx>y {
41+
returnx
42+
}
43+
returny
4444
}

‎src/0198.House-Robber/Solution_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,29 @@ func TestSolution2(t *testing.T) {
5252
}
5353
}
5454

55+
funcTestSolution3(t*testing.T) {
56+
//测试用例
57+
cases:= []struct {
58+
namestring
59+
inputs []int
60+
expectint
61+
}{
62+
{"TestCacse 1", []int{1,2,3,1},4},
63+
{"TestCacse 1", []int{2,7,9,3,1},12},
64+
}
65+
66+
//开始测试
67+
for_,c:=rangecases {
68+
t.Run(c.name,func(t*testing.T) {
69+
got:=rob3(c.inputs)
70+
if!reflect.DeepEqual(got,c.expect) {
71+
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
72+
c.expect,got,c.inputs)
73+
}
74+
})
75+
}
76+
}
77+
5578
//压力测试
5679
funcBenchmarkSolution(b*testing.B) {
5780

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp