746. Min Cost Climbing Stairs

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:

Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.

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].

给定一个数组,以0或1为起点,每次至少走一格,至多走两格,直至走出数组。把所有停留的位置的值相加,求最小和。

对于某一个位置,要是前一个位置“停”,则这个位置可“停”,可“不停”;要是前一个位置“不停”,则这个位置必须“停”。

换句话说,也就是当前位置“停”,前一位置可“停”或“不停”;当前位置“不停”,前一位置必须“停”。

用p表示该位置“停”的累加和,np表示该位置“不停”的累加和,则 p(i) = min(p(i-1), np(i-1)) + cost(i); np(i) = p(i-1) 

class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int p = cost[0];
        int np = 0;
        int temp = 0;
        for (int i=1; i<cost.size(); ++i) {
            temp = p;
            p = min(p, np) + cost[i];
            np = temp;
        }
        return min(p, np);
    }
};

 

posted @ 2017-12-18 21:01  Zzz...y  阅读(1916)  评论(0编辑  收藏  举报