【LeetCode】746. Min Cost Climbing Stairs 解题报告(Python)

本文介绍了一个经典的动态规划问题——爬楼梯。目标是最小化到达楼顶的花费,并提供了两种实现方式,包括逐步构建DP数组的方法。

作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/min-cost-climbing-stairs/description/

题目描述

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].

题目大意

爬楼梯,每次可以走1步或者2步,求走到顶的最小花费。其中,开始的位置可以是第一个位置或者第二个位置。

解题方法

动态规划

非常初级的动态规划的问题。需要做的是另外找一个列表保存节点的路径的代价,某个节点的路径的代价等于前两个节点的路径的代价和前两个节点对应的代价之和。最后返回的结果是倒数两个节点的代价和节点值之和的最小值。

class Solution(object):
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        costed = [0, 0]
        for i in xrange(2, len(cost)):
            costed.append(min(costed[i - 1] + cost[i - 1], costed[i - 2] + cost[i - 2]))
        return min(costed[-1] + cost[-1], costed[-2] + cost[-2])

二刷,同样的动态规划,提前把所有的dp状态声明出来,然后每一步的转移等于前两步的最小值+当前的值。因为需要上到最上面的楼梯,所以假设增加一个花费是0的楼梯。

class Solution:
    def minCostClimbingStairs(self, cost):
        """
        :type cost: List[int]
        :rtype: int
        """
        N = len(cost)
        cost.append(0)
        dp = [0] * (N + 1)
        dp[0] = cost[0]
        dp[1] = cost[1]
        for i in range(2, N + 1):
            dp[i] = min(dp[i - 1], dp[i - 2]) + cost[i]
        return dp[-1]

日期

2018 年 1 月 28 日
2018 年 11 月 17 日 —— 美妙的周末,美丽的天气

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值