内容:
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.
思路:计算上到某一级的花销为totol[i]
,递推式为totol[i] = min(totol[i - 2] + cost[i], totol[i - 1] +cost[i])
,上到顶的时候也可以是从倒数第一级上来的,也可以从倒数第二级上来的,所以最后返回min(totol[cost.size() - 1], totol[cost.size() - 2])
。
public:
int minCostClimbingStairs(vector<int>& cost) {
int cost_i_1=0,cost_i_2=0;
int n=cost.size();
int total_cost=0;
if(n==1||n==0)
{
return 0;
}
for(int i=2;i<=n;i++)
{
total_cost=min(cost[i-1]+cost_i_1,cost[i-2]+cost_i_2);
cost_i_2=cost_i_1;
cost_i_1=total_cost;
}
return total_cost;
}