问题:
爬楼梯问题(经典动态规划DP问题)
给定每阶台阶的消耗数组,每次可以选择爬一阶或者两阶,求爬到顶楼的最小消耗。
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].
解法:
经典动态规划DP
状态特点:选择爬一阶or两阶
动态转移方程:
dp[i]=min(dp[i-1]+cost[i-1] , dp[i-2]+cost[i-2])
临界状态:
dp[0]=0
dp[1]=0
简化动态转移中需要的变量,由动态转移方程,可知
每次计算,只需要dp[i-1]和dp[i-2],两个状态,则只增加两个变量dp_1和dp_2
代码参考:
1 class Solution { 2 public: 3 int minCostClimbingStairs(vector<int>& cost) { 4 int dp_2=0, dp_1=0, dp; 5 for(int i=2; i<=cost.size(); i++){ 6 dp = min(dp_2+cost[i-2], dp_1+cost[i-1]); 7 dp_2=dp_1; 8 dp_1=dp; 9 } 10 return dp; 11 } 12 };