746. Min Cost Climbing Stairs@python

时间:2023-03-09 07:07:19
746. Min Cost Climbing Stairs@python

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

题目地址: Min Cost Climbing Stairs

难度: Easy

题意: 

(1)从第一个元素或者第二个元素位置出发

(2)每次可以走一步或者走两步

(3)每到一个位置,都要收"过路费"

(4)返回需要的最少"过路费"

思路:

根据上面的第二个例子分析:

一个元素:  [1]   过路费为1
两个元素: [1, 100] 位置0 -> 跳出 过路费为1
三个元素: [1, 100, 1] 位置0 -> 位置2 -> 跳出 过路费为2
四个元素: [1, 100, 1, 1] 位置0 -> 位置2 -> 跳出 过路费为2
五个元素: [1, 100, 1, 1, 1] 位置0 -> 位置2 -> 位置3(或者位置4) -> 跳出 过路费为3
六个元素: [1, 100, 1, 1, 1, 100] 位置0 -> 位置2 -> 位置4 -> 跳出 过路费为3
七个元素: [1, 100, 1, 1, 1, 100, 1] 位置0 -> 位置2 -> 位置4 -> 位置6 -> 跳出 过路费4
八个元素: [1, 100, 1, 1, 1, 100, 1, 1] 位置0 -> 位置2 -> 位置4 -> 位置6 -> 跳出 过路费4
九个元素: [1, 100, 1, 1, 1, 100, 1, 1, 100] 位置0 -> 位置2 -> 位置4 -> 位置6 -> 位置7 -> 跳出 过路费5
十个元素: [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] 位置0 -> 位置2 -> 位置4 -> 位置6 -> 位置7 -> 位置9 -> 跳出 过路费6

采用动态规划方式,  dp[i] = min(dp[i-1]+cost[i-1], dp[i-2]+cost[i-2])

代码:

class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
step = [0] * (len(cost) + 1 )
i = 2
if len(cost) == 1:
return cost[0]
if len(cost) == 2:
return min(cost)
while i <= len(cost):
step[i] = min(step[i-1]+cost[i-1], step[i-2]+cost[i-2])
i += 1
return step[-1]

时间复杂度: O(n)

空间复杂度: O(n)