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 };
  • 相关阅读:
    线段拟合(带拉格朗日乘子,HGL)
    工作到位的标准
    Git的简单使用
    位移
    java日期格式化(util包下转成sql包下)
    java中继承的概念
    工作流驳回到指定连线节点上
    年终个人总结
    实现多条件查询 匹配数据库字段中多个数据
    activiti和SSH项目做整合
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278214.html
Copyright © 2011-2022 走看看