题目链接:
https://leetcode-cn.com/problems/min-cost-climbing-stairs/
动态规划:
设a(i)表示通过i阶梯花费的体力
则a(0) = cost(0)
a(1) = cost(1)
如下(粗糙做图。。)
【i-3】【i-2】【i-1】【i】
到达第i阶梯,可以通过i-2或者i-1,即a(i) = min{a(i-1), a(i-2)} + cost(i);
代码为:
int minCostClimbingStairs(int* cost, int costSize) {
int *a = (int *)malloc(sizeof(int) * costSize);
a[0] = cost[0];
a[1] = cost[1];
for(int i = 2; i < costSize+1; i++)
{
if(a[i-1] > a[i-2])
a[i] = a[i-2] + cost[i];
else
a[i] = a[i-1] + cost[i];
}
return a[costSize-1] > a[costSize-2] ? a[costSize-2] : a[costSize-1];
}