Timo66

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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  阅读(243)  评论(0编辑  收藏  举报