mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-08 08:50:15 +08:00
update 0198.打家劫舍: 更新 go 代码
This commit is contained in:
@ -154,22 +154,13 @@ class Solution:
|
|||||||
Go:
|
Go:
|
||||||
```Go
|
```Go
|
||||||
func rob(nums []int) int {
|
func rob(nums []int) int {
|
||||||
if len(nums)<1{
|
n := len(nums)
|
||||||
return 0
|
dp := make([]int, n+1) // dp[i]表示偷到第i家能够偷得的最大金额
|
||||||
|
dp[1] = nums[0]
|
||||||
|
for i := 2; i <= n; i++ {
|
||||||
|
dp[i] = max(dp[i-1], dp[i-2] + nums[i-1])
|
||||||
}
|
}
|
||||||
if len(nums)==1{
|
return dp[n]
|
||||||
return nums[0]
|
|
||||||
}
|
|
||||||
if len(nums)==2{
|
|
||||||
return max(nums[0],nums[1])
|
|
||||||
}
|
|
||||||
dp :=make([]int,len(nums))
|
|
||||||
dp[0]=nums[0]
|
|
||||||
dp[1]=max(nums[0],nums[1])
|
|
||||||
for i:=2;i<len(nums);i++{
|
|
||||||
dp[i]=max(dp[i-2]+nums[i],dp[i-1])
|
|
||||||
}
|
|
||||||
return dp[len(dp)-1]
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func max(a, b int) int {
|
func max(a, b int) int {
|
||||||
|
Reference in New Issue
Block a user