• 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 };
  • 相关阅读:
    Form表单提交数据的几种方式
    前端基础-HTML
    python入门函数详解
    Python作业编写
    Python入门数据类型详解
    Jquery选择器
    做外链接和有外链接区别
    三层架构
    drop,delete,truncate区别
    run()和star()区别
  • 原文地址:https://www.cnblogs.com/iamxiaoyubei/p/8278214.html
Copyright © 2020-2023  润新知