leetcode[746]:Min Cost Climbing Stairs

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/bless2015/article/details/88124498

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].

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int length = cost.length;
    	int f[] = new int[length+1];
    	//初始化
    	f[0]=cost[0];
    	f[1] = cost[1];
    	int value=0;
    	for (int i = 2; i < f.length; i++) {
    		if(i<length){
    		//防止越界
    			value = cost[i];
    		}else{
    			value=0;
    		}
    		f[i] =Math.min(f[i-1] ,f[i-2])+value;
		}
       return f[length]; 
    }
}

在这里插入图片描述

思路:
1、首先是求最大最小值问题,考虑用dp解决
2、看解空间的维数,发现是一维(非矩阵形式),所以直接声明一位数组 f[]
3、明确f[i]的含义为:第i次的代价和最小值。
4、写出状态转移方程f[i] = min(f[i-1]-f[i-2])+cost[i]
5、确定边界条件为f[0]和f[1],处理循环内的边界条件。

KEYWORDS:动态规划 最小代价爬楼梯

猜你喜欢

转载自blog.csdn.net/bless2015/article/details/88124498