[LC难题必须要解决系列][之][DP] Min Cost Climbing Stairs

Min Cost Climbing Stairs

https://leetcode.com/problems/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].

Intuition: 

这题要求最小cost,也是求极值问题,可以想到用DP。同时我们也可以清楚知道这和paint house一样也属于状态序列类问题,假设我们用一维数组f[i] 表示前i个楼梯要花的最小cost,这样我们的最后一步就是前n个楼梯要花的最小cost。 

方程:f[i] = Math.min(f[i-1], f[i-2]) + A[i];

初始:f[0] = A[0], f[1] = A[0] + A[1];

计算顺序:从0到n,结果取f[n-1];

Time conplexity: O(n);

    public int minCostClimbingStairs(int[] A) {
        int n = A.length;
        int[] f = new int[n];
        f[0] = A[0];
        f[1] = A[1];
        
        for (int i = 2; i < n; i ++){
            f[i] = Math.min(f[i-1], f[i-2]) + A[i];
        }
        
        return Math.min(f[n-2], f[n-1]);
    }

Climbing Stairs

https://leetcode.com/problems/climbing-stairs/

这个题也是一样能求极值问题想到DP,从最后一步考虑我们可以快速得到方程,f[i-1] + f[i-2]。这里就不详细写思路了。

class Solution {
    public int climbStairs(int n) {
        if (n <= 1) return 1;
        
        int[] f = new int[n];
        f[0] = 1;
        f[1] = 1;
        
        for (int i = 2; i < n; i ++){
            f[i] = f[i-1] + f[i-2];
        }
        
        return f[n-1] + f[n-2];
    }
}

 

posted on 2018-10-01 00:16 Timo66 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/timoBlog/p/9733860.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值