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 };
  • 相关阅读:
    MyBatis-Generator 最佳实践
    Http请求工具
    多线程编程-之并发编程:阻塞队列
    如数据不存在就插入,存在就更新
    MySQL触发器
    13.multi_match实现dis_max+tie_breaker
    12. tie_breaker的使用原因和使用方法
    11.best fields策略(dis_max参数设置)
    10.多shard场景下relevence score可能不准确
    9.boost权重控制
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278214.html
Copyright © 2011-2022 走看看