当前位置:网站首页>Daily practice of dynamic programming (2)
Daily practice of dynamic programming (2)
2022-08-02 09:08:00 【Dragon Roar @~】
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.Climb stairs with minimal cost
给你一个整数数组 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 中 in 的用法
- 向量组的线性相关性
- 为什么都推荐使用wordpress, 而不是 phpcms 这些国内的CMS呢?
- Bigder:41/100生产bug有哪些分类
- In a recent build figure SLAM, and locate the progress
- PyQt5安装配置(PyCharm) 亲测可用
- MySQL Workbench 安装及使用
- HCIA静态路由综合练习
- High imitation [Huawei consumer business official website] and wonderful animation analysis: practice embedding JS code in low-code platform
- Mysql Mac版下载安装教程
猜你喜欢
随机推荐
How Engineers Treat Open Source --- A veteran engineer's heartfelt words
pycharm的基本使用教程(1)
Hikari连接池源码解读
Redisson报异常attempt to unlock lock, not locked by current thread by node id解决方案
etcd implements large-scale service governance application combat
你有了解过这些架构设计,架构知识体系吗?(架构书籍推荐)
Jenkins--部署--3.1--代码提交自动触发jenkins--方式1
C语言基础_结构体
C Language Basics_Union
JS中的数组方法
四字节的float比八字结的long范围大???
nacos项目搭建
Jenkins--基础--6.2--Pipeline--语法--声明式
【论文阅读】Distilling the Knowledge in a Neural Network
leetcode:81. 搜索旋转排序数组 II
Analysis of software testing technology How far is Turing test from us
2022牛客暑期多校训练营4(ADHKLMN)
HCIP笔记第十三天
线程池的使用及ThreadPoolExecutor源码分析
练习40,小蓝的旅行【最短路】