描述
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].
解析
根据题意,想走完 n 阶台阶,每次可以向上跳 1 至 2 级,上台阶的总花费为 sum(cost[i]), i为所有踩过的台阶,求最小花费。这是一个动态规划的问题,只需要两个变量来遍历数组即可,时间复杂度为 O(N),空间复杂度为 O(1)。
解答
class Solution(object):
def minCostClimbingStairs(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
N = len(cost)
i = cost[0]
j = cost[1]
for x in range(2,N):
print(i,j)
tmp = min(i,j) + cost[x]
i = j
j = tmp
return min(i,j)
运行结果
Runtime: 44 ms, faster than 73.18% of Python online submissions for Min Cost Climbing Stairs.
Memory Usage: 11.8 MB, less than 81.16% of Python online submissions for Min Cost Climbing Stairs.
每日格言:成功的诀窍在于永不改动既定的方针。
请作者看小说 支付宝