当前位置:网站首页>动态规划每日一练(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];
}
};
边栏推荐
- MySQL安装与卸载详细教程
- High imitation [Huawei consumer business official website] and wonderful animation analysis: practice embedding JS code in low-code platform
- [OC学习笔记]weak的实现原理
- PyCharm usage tutorial (detailed version - graphic and text combination)
- 第3周学习:ResNet+ResNeXt
- Jenkins--基础--5.4--系统配置--全局工具配置
- location对象,navigator对象,history对象学习
- OneNote 教程,如何在 OneNote 中创建更多空间?
- OneNote Tutorial, How to Create More Spaces in OneNote?
- 二分类和多分类
猜你喜欢

工程师如何对待开源 --- 一个老工程师的肺腑之言

pycharm的基本使用教程(1)

PyCharm usage tutorial (more detailed, picture + text)

LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一:解题思路

Postman download localization of installation and use

MySQL Workbench 安装及使用

MySQL读写分离与主从延迟

RetinaFace: Single-stage Dense Face Localisation in the Wild

Redisson报异常attempt to unlock lock, not locked by current thread by node id解决方案

第3周学习:ResNet+ResNeXt
随机推荐
向量组的线性相关性
LeetCode_2357_使数组种所有元素都等于零
那些年我们踩过的 Flink 坑系列
Spark 系统性学习笔记系列
编程与哲学(2)——输出是为了更好的输入
EPSANet: An Efficient Pyramid Split Attention Block on Convolutional Neural Network
Ansible learning summary (11) - detailed explanation of forks and serial parameters of task parallel execution
力扣:第 304 场周赛
近期在SLAM建图和定位方面的进展
PyCharm usage tutorial (more detailed, picture + text)
EPSANet: An Efficient Pyramid Split Attention Block on Convolutional Neural Network
Three types of [OC learning notes] Block
工程师如何对待开源 --- 一个老工程师的肺腑之言
Flink 系统性学习笔记系列
Bigder:41/100生产bug有哪些分类
练习40,小蓝的旅行【最短路】
Seleniu screenshots code and assign name to the picture
ORBSLAM代码阅读
LeetCode第三题(Longest Substring Without Repeating Characters)三部曲之一:解题思路
(Note) AXIS ACASIS DT-3608 Dual-bay Hard Disk Array Box RAID Setting