leetcode746 Min Cost Climbing Stairs

 1 """
 2  On a staircase, the i-th step has some non-negative cost cost[i] assigned (0 indexed).
 3 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.
 4 Example 1:
 5 Input: cost = [10, 15, 20]
 6 Output: 15
 7 Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
 8 Example 2:
 9 Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
10 Output: 6
11 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
12 """
13 """
14 此题为简单的动态规划,按部就班算cost[i],即可找出动态方程
15 参考leetcode198
16 """
17 class Solution1(object):
18     def minCostClimbingStairs(self, cost):
19         n = len(cost)
20         if n == 0:
21             return 0
22         if n == 1:
23             return cost[0]
24         if n == 2:
25             return min(cost[0], cost[1])
26         for i in range(2, n):
27             cost[i] = min(cost[i-1]+cost[i], cost[i-2]+cost[i])
28             #bug 动态方程写为了min(cost[i-1], cost[i-2]+cost[i])
29         return min(cost[n-1], cost[n-2]) #!!!因为是爬到山顶,返回值在数组中

 

posted @ 2020-02-04 22:03  yawenw  阅读(131)  评论(0编辑  收藏  举报