classSolution{publicintminCostClimbingStairs(int[] cost){int[] dp =newint[cost.length +1];// Including the top// The top
dp[dp.length -1]=0;// The last cost
dp[dp.length -2]= cost[cost.length -1];// Start from the second cost from behindfor(int i = cost.length -2; i >=0;--i){// Current mim cost is the current cost + the minimum of the next 1 step and 2 steps cost
dp[i]= cost[i]+Math.min(dp[i +1], dp[i +2]);}// Decide starting from 0 or 1returnMath.min(dp[0], dp[1]);}}
O(1)空間優化
classSolution{publicintminCostClimbingStairs(int[] cost){// Start from the third cost from behindfor(int i = cost.length -3; i >=0;--i){// Current mim cost is the current cost + the minimum of the next 1 step and 2 steps cost
cost[i]= cost[i]+Math.min(cost[i +1], cost[i +2]);}// Decide starting from 0 or 1returnMath.min(cost[0], cost[1]);}}