首页 > 其他分享 >leetcode 746. Min Cost Climbing Stairs

leetcode 746. Min Cost Climbing Stairs

时间:2023-05-30 17:36:08浏览次数:41  
标签:cost 746 Min int min Solution step Cost dp

On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).

Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.

Example 1:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

Example 2:

Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
Output: 6
Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].

Note:

  1. cost will have a length in the range [2, 1000].
  2. Every cost[i] will be an integer in the range [0, 999].
class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        # mincost = min(mincost(n-1), mincost(n-2))+cost[n]
        # n = 2               
        a = cost[0]
        b = cost[1]
        for i in range(2, len(cost)):
            b,a = min(a, b)+cost[i], b
        return min(b, a)

注意:本质上是dp,dp[i]表示经过step i的min cost。

那么最后一步cost应该是min(dp[i], dp[i-1]) 表示要么最后一步是踩step i,cost就是dp[i],要么不踩step[i],必然是从step i-1过来的,跨了两步。

 

空间O(n)的解法:

Solution #1: Bottom-Up dynamic programming

Let dp[i] be the minimum cost to reach the i-th stair.

Base cases:

dp[0]=cost[0]
dp[1]=cost[1]

DP formula:

dp[i]=cost[i]+min(dp[i-1],dp[i-2])

Note: the top floor n can be reached from either 1 or 2 stairs away, return the minimum.

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int n=(int)cost.size();
        vector<int> dp(n);
        dp[0]=cost[0];
        dp[1]=cost[1];
        for (int i=2; i<n; ++i)
            dp[i]=cost[i]+min(dp[i-2],dp[i-1]);
        return min(dp[n-2],dp[n-1]);
    }
};

或者是:

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int [] mc = new int[cost.length + 1];
        mc[0] = cost[0];
        mc[1] = cost[1];
        
        for(int i = 2; i <= cost.length; i++){
            int costV = (i==cost.length)?0:cost[i];
            mc[i] = Math.min(mc[i-1] + costV, mc[i-2] + costV);
        }
        return mc[cost.length];
    }
}

 

标签:cost,746,Min,int,min,Solution,step,Cost,dp
From: https://blog.51cto.com/u_11908275/6381002

相关文章

  • nacos服务下线操作时报错:The Raft Group [naming_instance_metadata] did not find th
    【问题描述】caused:errCode:500,errMsg:dometadataoperationfailed;caused:com.alibaba.nacos.consistency.exception.ConsistencyException:TheRaftGroup[naming_instance_metadata]didnotfindtheLeadernode;caused:TheRaftGroup[naming_instance_metad......
  • Focus On 3D Terrain Programming三维地形渲染-Trent Polack-2003
    前言:你有多少次访问过你最喜欢的编程论坛或邮件列表,并对大量关于地形渲染算法的帖子感到惊讶,这些帖子似乎从各个角度向你袭来?地形渲染似乎是当今业余程序员最喜欢的主题;它是一个很好的门户网站,可以了解更高要求的问题及其解决方案。然而,地形渲染决不是一个简单的问题,特定的解决方......
  • redmine 127访问成功,其他机器不能访问
    添加防火墙入站规则......
  • 【Oracle】Resize your Oracle datafiles down to the minimum without ORA-03297
      --Innon-multitenantDBsetlinesize1000pagesize0feedbackofftrimspoolonwithhwmas(--gethighestblockidfromeachdatafiles(fromx$ktfbueaswedon'tneedalljoinsfromdba_extents)select/*+materialize*/ktfbuesegtsnts......
  • 【Oracle】Oracle Database Administration 2019 Certified Professional Certificati
     说明:1.目前题库100%覆盖考题,准确率84%。2.若需要优质烤券,请私信,留下你的WX。(官方250刀,本店只需要1500RMB包含100%完整题库以及考试经验分享)3.本条信息长期有效。考试题量:85通过分数:84%1、WhichtwoaretrueaboutreclaimingspaceusedbyFlashbacklogsinOracle......
  • canal+rabbitmq: Could not convert incoming message with content-type [null]
    SpringBoot整合Canal+RabbitMQ实现监听MySQL数据库同步更新Redis缓存,编写RabbitMQ消费端监听同步缓存。接收消息是字符串返回的是字节数据,eg:-30,-128,-100,-25,-126,-71,-27,-81,-71,-25,-126,-71,-30,-128,-99使用了jackson的converter后,报了如下的异常:Causedby:......
  • catchAdmin+phpEmailer批量发邮件
    前端参数  后端逻辑//多个邮箱配置publicfunctionsystem(){$email_type=input('email_type','1');$field='id,smtp,smtp_port,sender_email_adress,smtp_name,smtp_code,encryption_type';$where[]=......
  • 基于 Mindspore 框架与 ModelArts 平台的 MNIST 手写体识别实验
    简介实验包含2部分:基于Mindspore框架的模型本地训练及预测基于Modelarts平台和PyTorch框架的模型训练及部署基于Mindspore框架的模型本地训练及预测本例子会实现一个简单的图片分类的功能,整体流程如下:处理需要的数据集,这里使用了MNIST数据集。定义一个网络,这......
  • admin
    admin监控1.入門admin-server依賴<dependency><groupId>de.codecentric</groupId><artifactId>spring-boot-admin-starter-server</artifactId></dependency><dependency><grou......
  • TransformMine图片表格化安卓APP
    TransformMine图片表格化安卓APP展示: 部分代码:<?xmlversion="1.0"encoding="utf-8"?><com.scwang.smart.refresh.layout.SmartRefreshLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://s......