使用最小花費爬樓梯

在這裏插入圖片描述
題目鏈接:
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]; 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章