DP Topic 3 Climb the stairs with minimum cost

topic:

Idea:

        According to the meaning of the question, we first clarify the meaning of dp array i. It is obvious here that i is the minimum cost of the corresponding ladder,

Secondly, in dp initialization, our dp[0] and dp[1] are 0 costs,

This is what we can choose. When dp[2] is reached, it is our min(dp[0] + cost[0],dp[1] + cost[1])   

That is, this is our recursive formula: the minimum cost to reach the current ladder + the cost of the current ladder = the target ladder reached

即 dp[i] = min(dp[i - 1] + cost[i - 1],dp[i - 2] + cost[i - 2]);

The code is explained in detail below:

int minCostClimbingStairs(vector<int>& cost) 
{
	// 计算台阶数量
	int n =cost.size();
    
    // 定义 dp 数组,其中 dp[i]  
	// i 所对应的是相应台阶的最少花费
    vector<int>dp(n + 1,0);
    
    // dp 数组初始化,由于可以选择在 0 或 1 台阶开始爬楼梯
    // 所以 先计算第三个台阶的最少花费
    dp[2] = min(cost[0],cost[1]);
    
    for(int i = 3;i <= n;++i)
    {
    	// 递推公式,达到当前阶梯的最少花费 + 当前阶梯需要的花费 = 到达的目标阶梯
    	dp[i] = min(dp[i - 1] + cost[i - 1],dp[i - 2] + cost[i - 2]);
	}
	
	/*
	
	打印 dp 数组查看是否是自己需要的效果
	验证答案
	debugv(dp);
	
	*/
    
    // 输出对应阶梯的最少花费
	return dp[n];
}

Last commit:

おすすめ

転載: blog.csdn.net/hacker_51/article/details/132875184