当前位置: 代码迷 >> 综合 >> 746. 使用最小花费爬楼梯(min-cost-climbing-stairs)
  详细解决方案

746. 使用最小花费爬楼梯(min-cost-climbing-stairs)

热度:64   发布时间:2024-01-11 13:29:51.0

746. 使用最小花费爬楼梯(min-cost-climbing-stairs)

数组的每个索引做为一个阶梯,第 i个阶梯对应着一个非负数的体力花费值 cost[i](索引从0开始)。每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。示例 1:输入: cost = [10, 15, 20]
输出: 15
解释: 最低花费是从cost[1]开始,然后走两步即可到阶梯顶,一共花费15。
示例 2:输入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
输出: 6
解释: 最低花费方式是从cost[0]开始,逐个经过那些1,跳过cost[3],一共花费6。
注意:cost 的长度将会在 [2, 1000]。
每一个 cost[i] 将会是一个Integer类型,范围为 [0, 999]。
  • 分析

    比爬台阶问题,多了一个花费,题本身不难,但是理解清题意还是稍微费点劲
    

d p [ n ] = { 0 n = 1 , 2 m i n { d p [ n ? 1 ] + c o s t [ n ? 1 ] , d p [ n ? 2 ] + c o s t [ n ? 2 ] } n > 2 dp[n]=\left\{ \begin{aligned} & 0 & n=1,2 \\ &min\{dp[n-1]+cost[n-1],dp[n-2]+cost[n-2]\} &n>2 \end{aligned} \right. dp[n]={ ?0min{ dp[n?1]+cost[n?1],dp[n?2]+cost[n?2]}?n=1,2n>2?

  • code
package main
import "fmt"
// 10 15 20
//15
func minCostClimbingStairs(cost []int) int {
    c:=make([]int,len(cost)+1)c[0]=0c[1]=0for i:=2;i<=len(cost);i++{
    min:=cost[i-1]+c[i-1]max:=cost[i-2]+c[i-2]if min>max{
    min,max=max,min}c[i]=min}return  c[len(cost)]
}func main(){
    fmt.Println(minCostClimbingStairs([]int{
    10,15,20}))fmt.Println(minCostClimbingStairs([]int{
    1, 100, 1, 1, 1, 100, 1, 1, 100, 1}))
}
  相关解决方案