Leetcode - 746 Min Cost Climbing Stairs (Easy)
题目描述:给定一个数组,每个元素表示爬到台阶所花费的体力,每次能够向上爬一个或者两个台阶,求最小体力花费的爬法。
Input: cost = [10, 15, 20]
Output: 15
Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
解题思路:和爬台阶的算法类似,只不过增加了一个花费的体力,转移方程为 dp[i] = cost[i] + Min(dp[i - 1], dp[i - 2])。
public int minCostClimbingStairs(int[] cost) {
int n = cost.length;
int[] dp = new int[n];
dp[0] = cost[0];
dp[1] = cost[1];
for (int i = 2; i < n; i++) {
dp[i] = cost[i] + Math.min(dp[i - 1], dp[i - 2]);
}
return Math.min(dp[n - 1], dp[n - 2]);
}