File tree Expand file tree Collapse file tree 1 file changed +23
-6
lines changed Expand file tree Collapse file tree 1 file changed +23
-6
lines changed Original file line number Diff line number Diff line change 66
66
67
67
所以初始化代码为:
68
68
69
- ```
69
+ ``` CPP
70
70
vector<int > dp (cost.size());
71
71
dp[ 0] = cost[ 0] ;
72
72
dp[ 1] = cost[ 1] ;
@@ -201,15 +201,32 @@ public:
201
201
202
202
203
203
### Java
204
+
204
205
``` Java
206
+ // 方式一:第一步支付费用
205
207
class Solution {
206
208
public int minCostClimbingStairs (int [] cost ) {
207
- if (cost == null || cost.length == 0) {
208
- return 0;
209
- }
210
- if (cost.length == 1) {
211
- return cost[0];
209
+ int len = cost. length;
210
+ int [] dp = new int [len + 1 ];
211
+
212
+ // 从下标为 0 或下标为 1 的台阶开始,因此支付费用为0
213
+ dp[0 ] = 0 ;
214
+ dp[1 ] = 0 ;
215
+
216
+ // 计算到达每一层台阶的最小费用
217
+ for (int i = 2 ; i <= len; i++ ) {
218
+ dp[i] = Math . min(dp[i - 1 ] + cost[i - 1 ], dp[i - 2 ] + cost[i - 2 ]);
212
219
}
220
+
221
+ return dp[len];
222
+ }
223
+ }
224
+ ```
225
+
226
+ ``` Java
227
+ // 方式二:第一步不支付费用
228
+ class Solution {
229
+ public int minCostClimbingStairs (int [] cost ) {
213
230
int [] dp = new int [cost. length];
214
231
dp[0 ] = cost[0 ];
215
232
dp[1 ] = cost[1 ];
You can’t perform that action at this time.
0 commit comments