您的位置:首页 > 大数据 > 人工智能

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

2018-01-28 19:07 471 查看

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

标签(空格分隔): LeetCode

题目地址: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:

cost will have a length in the range [2, 1000].

Every cost[i] will be an integer in the range [0, 999].

Ways

方法一:

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

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


Date

2018 年 1 月 28 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: