这题明显属于动态规划的题目。首先给出题目:

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:

cost will have a length in the range [2, 1000].
Every cost[i] will be an integer in the range [0, 999].

题意为给出每级阶梯的消耗,求爬完所有楼梯的最小消耗。根据题意,我们很容易想到用动态规划来解这道题。动态规划的核心在于递推公式,在这里,我们可以想到假如我在第N级阶梯,则肯定是从N-2或者是N-1级阶梯走过来的,那么只要知道N-1级阶梯的最小消耗和N-2级阶梯的最小消耗,然后求两者最小即可。知道这个递推公式就很好办了,我们只要知道每级的最小消耗,当从该层可以到达顶层后,就可以把结果放入结果集了。然后我们需要在结果集中再求出最小的消耗即可。

下面为代码:

static int main(vector<int>& cost) {
    int lcost = cost[0], rcost = cost[1];
    for (int i = 2; i < cost.size(); i++) {
        int nlcost = lcost + cost[i];
        int nrcost = rcost + cost[i];
        int fcost = nlcost < nrcost ? nlcost : nrcost;
        lcost = rcost; rcost = fcost;
    }
    return lcost < rcost ? lcost : rcost;
}
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day