当前位置:网站首页>动态规划每日一练(2)
动态规划每日一练(2)
2022-08-02 08:40:00 【恶龙咆哮@~】
1.爬楼梯
假设你正在爬楼梯。需要 n 阶你才能到达楼顶。
每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?
我们用 f(x)f(x) 表示爬到第 xx 级台阶的方案数,考虑最后一步可能跨了一级台阶,也可能跨了两级台阶,所以我们可以列出如下式子:
f(x) = f(x - 1) + f(x - 2)
它意味着爬到第 xx 级台阶的方案数是爬到第 x - 1x−1 级台阶的方案数和爬到第 x - 2x−2 级台阶的方案数的和。很好理解,因为每次只能爬 11 级或 22 级,所以 f(x)f(x) 只能从 f(x - 1)f(x−1) 和 f(x - 2)f(x−2) 转移过来,而这里要统计方案总数,我们就需要对这两项的贡献求和。
class Solution {
public:
int climbStairs(int n) {
if(n<=2)
{
return n;
}
else{
int p=0,q=1,s=1;
for(int i=2;i<=n;i++)
{
p=q;
q=s;
s=q+p;
}
return s;
}
}
};
2.使用最少花费爬楼梯
给你一个整数数组 cost ,其中 cost[i] 是从楼梯第 i 个台阶向上爬需要支付的费用。一旦你支付此费用,即可选择向上爬一个或者两个台阶。
你可以选择从下标为 0 或下标为 1 的台阶开始爬楼梯。
请你计算并返回达到楼梯顶部的最低花费。
题解:dp问题
dp[i]=min(dp[i−1]+cost[i−1],dp[i−2]+cost[i−2])
class Solution {
public:
int minCostClimbingStairs(vector<int>& cost) {
int n=cost.size();
vector<int> dp(n+1);
dp[0]=0;
dp[1]=0;
for(int i=2;i<=n;i++)
{
dp[i]=min(dp[i-1]+cost[i-1],dp[i-2]+cost[i-2]);
}
return dp[n];
}
};
边栏推荐
猜你喜欢
随机推荐
The custom table form
为什么都推荐使用wordpress, 而不是 phpcms 这些国内的CMS呢?
抓包工具Charles修改Response步骤
RetinaFace: Single-stage Dense Face Localisation in the Wild
(Note)阿克西斯ACASIS DT-3608双盘位硬盘阵列盒RAID设置
Biotin-C6-amine|N-biotinyl-1,6-hexanediamine|CAS: 65953-56-2
R language plotly visualization: plotly visualizes the scatter plot of the actual value of the regression model and the predicted value of the regression, analyzes the prediction performance of the re
Redisson的看门狗机制
C语言_条件编译
The packet capture tool Charles modifies the Response step
构建Flink第一个应用程序
积分商城商品供应商选择的三个要求
Jenkins--部署--3.1--代码提交自动触发jenkins--方式1
近期在SLAM建图和定位方面的进展
编程与哲学(2)——输出是为了更好的输入
二分类和多分类
TiFlash 存储层概览
PostgreSQL learning summary (11) - PostgreSQL commonly used high-availability cluster solutions
【Flink 问题】Flink 如何提交轻量jar包 依赖该如何存放 会遇到哪些问题
pnpm:简介