zoukankan      html  css  js  c++  java
  • 746. Min Cost Climbing Stairs

    #week5

    问题:

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

    分析:

    动态规划问题

    则需要思考每一个步的子问题是什么,这个子问题又能够由上一步或者哪些子问题来解决

    这里,把爬到每一个楼梯的耗费作为子问题f[i]

    则可以得到状态转移方程:

    f[i]=min(f[i-1],f[i-2])+cost[i];

    初始化

    f[0]=cost[0] f[1]=cost[1]

    题解:

     1 class Solution {
     2 public:
     3     int min(int a, int b) {
     4         if (a<b) return a;
     5         return b;
     6     }
     7     int minCostClimbingStairs(vector<int>& cost) {
     8         int size = cost.size();
     9         int f[size];
    10         f[0] = cost[0];
    11         f[1] = cost[1];
    12         for (int i = 2; i < cost.size(); i++) {
    13             f[i] = min(f[i-1]+cost[i], f[i-2]+cost[i]);
    14         }
    15         return min(f[size-1],f[size-2]);
    16     }
    17 };
  • 相关阅读:
    kubernetes dashboard 二次开发
    grafana二次开发
    Harbor 定制页面 和 二次开发指南
    spring boot 知识点1
    spring boot2.1读取 apollo 配置中心3
    apollo 部门管理
    spring boot2.1读取 apollo 配置中心2
    a 产生一个int数组,长度为100,并向其中随机插入1-100,并且不能重复。
    Net上机考试
    Net(ASP.NET)程序设计
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278214.html
Copyright © 2011-2022 走看看