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 };
  • 相关阅读:
    python3 socketserver服务端
    python3 组合的用法
    python3 面向对象高级一些的
    python3 继承原理
    python3 对象之间的交互
    hadoop配置、运行错误总结
    Hadoop配置项整理(mapred-site.xml)
    Hadoop配置项整理(core-site.xml)
    Hadoop配置项整理(hdfs-site.xml)
    Linux Shell 按Tab键不能补全
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278214.html
Copyright © 2011-2022 走看看