On a staircase, the i
-th step has some non-negative cost cost[i]
assigned (0 indexed).
Once you pay the cost, you can either climb one or two steps. You need to find minimum cost to reach the top of the floor, and you can either start from the step with index 0, or the step with index 1.
Example 1:
Input: cost = [10, 15, 20] Output: 15 Explanation: Cheapest is start on cost[1], pay that cost and go to the top.
Example 2:
Input: cost = [1, 100, 1, 1, 1, 100, 1, 1, 100, 1] Output: 6 Explanation: Cheapest is start on cost[0], and only step on 1s, skipping cost[3].
Note:
cost
will have a length in the range[2, 1000]
.- Every
cost[i]
will be an integer in the range[0, 999]
.
数组的每个索引做为一个阶梯,第 i
个阶梯对应着一个非负数的体力花费值 cost[i]
(索引从0开始)。
每当你爬上一个阶梯你都要花费对应的体力花费值,然后你可以选择继续爬一个阶梯或者爬两个阶梯。
您需要找到达到楼层顶部的最低花费。在开始时,你可以选择从索引为 0 或 1 的元素作为初始阶梯。
示例 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]
。
题解:给一个数组,表示每登一级台阶需要花费的成本,每次能登一步或者两步,求登到顶,需要花费的最少的成本?这道题是一道典型的动态规划的题目,甚至都有点类似于贪心算法,先保存该数组起始的第一个成本和第二个成本,因为后续攀登都要从登一步或登两步开始攀登。然后开始计算相应的成本开销。
public int minCostClimbingStairs(int[] cost)
{
int length = cost.length; //典型的动态规划
int[] dp = new int[length];
dp[0] = cost[0]; //第一个元素
dp[1] = cost[1]; //第二个元素
for(int i = 2; i < length; i++) //从第3个元素开始
{
int curr = cost[i];
dp[i] = Math.min(dp[i - 1],dp[i - 2]) + curr; //每次比较当前元素与之前两步的元素中的最小值,其实该动态规划算法有点类似于贪心算法
}
return Math.min(dp[cost.length - 1],dp[cost.length - 2]);
}