• [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];
        }
    }
  • 相关阅读:
    js reduce函数基本知识和应用
    maven打包命令
    js处理后端返回的不同文件的流
    SQL 优化过程
    触发器点滴
    查询数据库中所有包含某文本的存储过程、视图和函数的SQL
    SQL Server FOR XML PATH 语句的应用
    vue实现扫码枪监听
    ASP.NET网络编程中经常用到的27个函数集
    收集
  • 原文地址:https://www.cnblogs.com/timoBlog/p/9733860.html
Copyright © 2020-2023  润新知