題目鏈接:
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];
}