746. Min Cost Climbing Stairs

746. Min Cost Climbing Stairs

Question

You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.

You can either start from the step with index 0, or the step with index 1.

Return the minimum cost to reach the top of the floor.

Solution

动态规划,每一个新位置的等于前一个位置加上其cost和前两个位置加上cost的较小值。

Code

1
2
3
4
5
6
7
8
9
class Solution {
public int minCostClimbingStairs(int[] cost) {
int[] dp = new int[cost.length+1];
for(int i = 2; i <= cost.length; i++){
dp[i] = Math.min(dp[i-1] + cost[i-1], dp[i-2] + cost[i-2]);
}
return dp[cost.length];
}
}
Author

Xander

Posted on

2022-07-10

Updated on

2022-07-11

Licensed under

Comments