力扣746 使用最小花费爬楼梯

问题描述:

给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。

你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。

请你计算并返回达到楼梯顶部的最低花费。

示例一:

输入:cost = [10,15,20]
输出:15
解释:你将从下标为 1 的台阶开始。

  • 支付 15 ,向上爬两个台阶,到达楼梯顶部。
    总花费为 15
    示例二:

输入:cost = [1,100,1,1,1,100,1,1,100,1]
输出:6
解释:你将从下标为 0 的台阶开始。

  • 支付 1 ,向上爬两个台阶,到达下标为 2 的台阶。
  • 支付 1 ,向上爬两个台阶,到达下标为 4 的台阶。
  • 支付 1 ,向上爬两个台阶,到达下标为 6 的台阶。
  • 支付 1 ,向上爬一个台阶,到达下标为 7 的台阶。
  • 支付 1 ,向上爬两个台阶,到达下标为 9 的台阶。
  • 支付 1 ,向上爬一个台阶,到达楼梯顶部。
    总花费为 6 。
    问题解决:

方法一:DFS(注意:此方法运行超时需要优化)

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=1010;
//cost是每步的花费向量,x表示当前考虑的步数。
int dfs(vector<int> &cost,int x)
{
    if(x==1||x==0) return 0;//当步数为 0 或 1 时,花费为 0,因为没有步数就没有花费。
    else return min(dfs(cost,x-1)+cost[x-1],dfs(cost,x-2)+cost[x-2]);//对于其他步数x,选择从x - 1步到达x步(花费为dfs(cost, x - 1)+cost[x - 1])或者从x - 2步到达x步(花费为dfs(cost, x - 2)+cost[x - 2])中的较小花费。
}

int main()
{

    vector<int> cost{1,100,1,1,1,100,1,1,100,1};
    int n=cost.size();
    int ans=dfs(cost,n);
    printf("%d",ans);
    return 0;
}

方法二:记忆化搜索

#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=1010;
int dfs(vector<int> &cost,int x)
{
    int mem[x];
    if(mem[x]) return mem[x];
    int sum=0;
    if(x==1||x==0) return 0;
    else sum = min(dfs(cost,x-1)+cost[x-1],dfs(cost,x-2)+cost[x-2]);
    mem[x]=sum;
    return sum;
}

int main()
{
    vector<int> cost{1,100,1,1,1,100,1,1,100,1};
    int n=cost.size();
    int ans=dfs(cost,n);
    printf("%d",ans);
    return 0;
}

方法三:递推


#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std;
const int N=1010;

int main()
{
    vector<int> cost{1,100,1,1,1,100,1,1,100,1};
    int n=cost.size();//表示这个 “爬楼梯” 场景中的总步数(包含起始位置,这里可以理解为从第 0 步开始)。
   int f[N];//用于存储动态规划过程中的状态值,即到达每一步的最小花费
   f[0]=f[1]=0;//初始化动态规划的边界条件
 
   for(int i=2;i<=n;i++)
   {
     f[i]=min(f[i-1]+cost[i-1],f[i-2]+cost[i-2]);
   }//这是动态规划的状态转移方程。对于第i步,到达它有两种方式:一种是从第i - 1步迈一步过来,此时总花费就是到达第i - 1步的最小花费f[i - 1]加上第i步本身的花费cost[i - 1];另一种是从第i - 2步迈两步过来,总花费就是到达第i - 2步的最小花费f[i - 2]加上第i步的花费cost[i - 2]。取这两种方式中的较小花费作为到达第i步的最小花费,并存储到f[i]中
printf("%d",f[n]);
    return 0;
}
posted @   爱学习的小许?  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
点击右上角即可分享
微信分享提示