Merge pull request #1816 from juguagua/leetcode-modify-the-code-of-the-greedy

更新贪心部分:至 “跳跃游戏”
This commit is contained in:
程序员Carl
2022-12-15 09:51:11 +08:00
committed by GitHub
3 changed files with 28 additions and 44 deletions

View File

@ -72,13 +72,13 @@ public:
```
## 总结
这道题目关键点在于:不用拘泥于每次究竟跳几步,而是看覆盖范围,覆盖范围内一定是可以跳过来的,不用管是怎么跳的。
这道题目关键点在于:不用拘泥于每次究竟跳几步,而是看覆盖范围,覆盖范围内一定是可以跳过来的,不用管是怎么跳的。
大家可以看出思路想出来了,代码还是非常简单的。
一些同学可能感觉,我在讲贪心系列的时候,题目和题目之间貌似没有什么联系?
**是真的就是没什么联系,因为贪心无套路!**没有个整体的贪心框架解决一列问题,只能是接触各种类型的题目锻炼自己的贪心思维!
**是真的就是没什么联系,因为贪心无套路!**没有个整体的贪心框架解决一列问题,只能是接触各种类型的题目锻炼自己的贪心思维!
## 其他语言版本
@ -133,24 +133,6 @@ class Solution:
```
### Go
```Go
func canJUmp(nums []int) bool {
if len(nums)<=1{
return true
}
dp:=make([]bool,len(nums))
dp[0]=true
for i:=1;i<len(nums);i++{
for j:=i-1;j>=0;j--{
if dp[j]&&nums[j]+j>=i{
dp[i]=true
break
}
}
}
return dp[len(nums)-1]
}
```
```go
// 贪心

View File

@ -46,7 +46,7 @@
### 贪心算法
这道题目可能我们只会想,选一个低的买入,选个高的卖,选一个低的买入.....循环反复。
这道题目可能我们只会想,选一个低的买入,选个高的卖,选一个低的买入.....循环反复。
**如果想到其实最终利润是可以分解的,那么本题就很容易了!**
@ -198,38 +198,40 @@ class Solution:
### Go:
```golang
//贪心算法
贪心算法
```go
func maxProfit(prices []int) int {
var sum int
for i := 1; i < len(prices); i++ {
// 累加每次大于0的交易
if prices[i]-prices[i-1] > 0 {
sum += prices[i]-prices[i-1]
if prices[i] - prices[i-1] > 0 {
sum += prices[i] - prices[i-1]
}
}
return sum
}
```
```golang
//确定售卖点
动态规划
```go
func maxProfit(prices []int) int {
var result,buy int
prices=append(prices,0)//在price末尾加个0防止price一直递增
/**
思路:检查后一个元素是否大于当前元素,如果小于,则表明这是一个售卖点,当前元素的值减去购买时候的值
如果不小于,说明后面有更好的售卖点,
**/
for i:=0;i<len(prices)-1;i++{
if prices[i]>prices[i+1]{
result+=prices[i]-prices[buy]
buy=i+1
}else if prices[buy]>prices[i]{//更改最低购买点
buy=i
}
dp := make([][]int, len(prices))
for i := 0; i < len(dp); i++ {
dp[i] = make([]int, 2)
}
return result
// dp[i][0]表示在状态i不持有股票的现金dp[i][1]为持有股票的现金
dp[0][0], dp[0][1] = 0, -prices[0]
for i := 1; i < len(prices); i++ {
dp[i][0] = max(dp[i-1][0], dp[i-1][1] + prices[i])
dp[i][1] = max(dp[i-1][0] - prices[i], dp[i-1][1])
}
return dp[len(prices)-1][0]
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
```

View File

@ -286,7 +286,7 @@ class Solution:
### Go
**贪心**
```golang
```go
func wiggleMaxLength(nums []int) int {
n := len(nums)
if n < 2 {
@ -309,7 +309,7 @@ func wiggleMaxLength(nums []int) int {
```
**动态规划**
```golang
```go
func wiggleMaxLength(nums []int) int {
n := len(nums)
if n <= 1 {