zoukankan      html  css  js  c++  java
  • [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];
        }
    }
  • 相关阅读:
    JAVA日报
    JAVA日报
    JAVA日报
    JAVA
    leetcode刷题笔记 222题 完全二叉树的节点个数
    leetcode刷题笔记 221题 最大正方形
    leetcode刷题笔记 220题 存在重复元素 III
    leetcode刷题笔记 219题 存在重复元素 II
    leetcode刷题笔记 218题 天际线问题
    leetcode刷题笔记 216题 组合总和 III
  • 原文地址:https://www.cnblogs.com/timoBlog/p/9733860.html
Copyright © 2011-2022 走看看