746. Min Cost Climbing Stairs 有问题


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

假设每一个台阶花费多少钱,一次可以上一个台阶或者两个台阶,计算最少的花费。

优先考虑跨台阶走

每走一步之前,先看下一台阶和下下个台阶谁比较便宜,走便宜的,如果一样花费,就走下下个台阶。

但是有一种情况是不符合的:【10,15,29】   走第二个台阶会比较少

如果走到15,是不需要走29的,也就是有的情况是不需要加上最后一阶的

其实就是在i=len(cost)-3时,需要比较的不是i和i+1而是要比较i+1和i,i+2之和

优先走两个台阶也不科学了。



新思路:如果是三步进行相比,是中间一步花费少还是首尾两步花费少。如果选了中间一步,选择这一步后的三步再进行比较;如果选了首尾两步,那就选择尾部之后的三步进行比较。

在不能被3整除时,最后剩下2个或者1个,额外进行处理。


难道要4个进行比较?我要疯了!



原来这个问题要用到的算法是动态规划。

到第n个台阶的mincost是到第n-1个台阶的mincost和到第n-2个台阶的Mincost的小者再加上第n个台阶的花费。

最后一个台阶的mincost则是到前一个台阶的mincost和到前前一个台阶的Mincost再加上第n个台阶的花费的小者

另外第0个和第一个台阶的花费分别是cost[0]、cost[1]


时间复杂度O(n)

空间复杂度O(n)

空间复杂度可以优化:

不用一个列表存储,而只用a,b,c


空间复杂度为常数。

如果用递归?TLE,

但是用了哈希表就可以了?

这是不是就是动态规划的优点,而递归加上哈希表就有点动态规划的意思了。

不明白不明白,不想看了


猜你喜欢

转载自blog.csdn.net/zhangdamengcsdn/article/details/80002257
今日推荐