内容:
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;
}
爬楼梯最小花费算法
本文介绍了一种计算爬楼梯最小成本的算法。通过递推公式计算到达每一阶楼梯所需的最低费用,采用动态规划思想,从底部开始逐步计算直到顶部。
437

被折叠的 条评论
为什么被折叠?



