數組的每一個索引作爲一個階梯,第 i個階梯對應着一個非負數的體力花費值 costi。java
每當你爬上一個階梯你都要花費對應的體力花費值,而後你能夠選擇繼續爬一個階梯或者爬兩個階梯。數組
您須要找到達到樓層頂部的最低花費。在開始時,你能夠選擇從索引爲 0 或 1 的元素做爲初始階梯。ide
示例 1:spa
輸入: cost = [10, 15, 20]
輸出: 15
解釋: 最低花費是從cost[1]開始,而後走兩步便可到階梯頂,一共花費15。
示例 2:code
輸入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
輸出: 6
解釋: 最低花費方式是從cost[0]開始,逐個通過那些1,跳過cost[3],一共花費6。
注意:索引
cost 的長度將會在 [2, 1000]。
每個 cost[i] 將會是一個Integer類型,範圍爲 [0, 999]。get
class Solution { public int minCostClimbingStairs(int[] cost) { if(cost.length==2) return Math.max(cost[0],cost[1]); int[] dp=new int[cost.length+1]; dp[0]=0;dp[1]=cost[0]; for(int i=2;i<cost.length+1;i++){ dp[i]=Math.min(dp[i-1],dp[i-2])+cost[i-1]; } return Math.min(dp[cost.length],dp[cost.length-1]); } }
數組的每一個索引作爲一個階梯,第 i個階梯對應着一個非負數的體力花費值 costi。it
每當你爬上一個階梯你都要花費對應的體力花費值,而後你能夠選擇繼續爬一個階梯或者爬兩個階梯。io
您須要找到達到樓層頂部的最低花費。在開始時,你能夠選擇從索引爲 0 或 1 的元素做爲初始階梯。class
示例 1:
輸入: cost = [10, 15, 20]
輸出: 15
解釋: 最低花費是從cost[1]開始,而後走兩步便可到階梯頂,一共花費15。
示例 2:
輸入: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1]
輸出: 6
解釋: 最低花費方式是從cost[0]開始,逐個通過那些1,跳過cost[3],一共花費6。
注意:
cost 的長度將會在 [2, 1000]。
每個 cost[i] 將會是一個Integer類型,範圍爲 [0, 999]。
class Solution { public int minCostClimbingStairs(int[] cost) { if(cost.length==2) return Math.max(cost[0],cost[1]); int[] dp=new int[cost.length+1]; dp[0]=0;dp[1]=cost[0]; for(int i=2;i<cost.length+1;i++){ dp[i]=Math.min(dp[i-1],dp[i-2])+cost[i-1]; } return Math.min(dp[cost.length],dp[cost.length-1]); } }