当前位置:网站首页>Dynamic programming -- simple question type of climbing stairs
Dynamic programming -- simple question type of climbing stairs
2022-07-28 06:39:00 【Step by step b】
climb stairs
Suppose you need to climb n It takes steps to reach the roof , Every time you climb 1 or 2 A stair , So how many different ways can you climb to the roof ?
analysis
Define an array dp[i] , It means to climb to the first i The first floor has dp[i] Methods .
Array dp[i] Derived from two directions :
dp[i-1], On i-1 Stairs on the first floor dp[i-1] Methods , The next step is dp[i];
dp[i-2], On i-2 Stairs on the first floor dp[i-2] Methods , The next two steps are dp[i];
namely dp[i] = dp[i-1]+dp[i-2]
Code implementation
#include<iostream>
using namespace std;
class Solution {
public:
int ClimbStairs(int n) {
int dp[3];
dp[1] = 1;
dp[2] = 2;
if (n < 3) return dp[n];
for (int i = 3; i <= n; i++) {
int sum = dp[1] + dp[2];
dp[1] = dp[2];
dp[2] = sum;
}
return dp[2];
}
};
int main() {
Solution Q;
int n;
cin>>n;
cout<<Q.ClimbStairs(n);
}
边栏推荐
猜你喜欢
随机推荐
2022-05-24 SpEL使用
Use and safe shutdown of qthread thread in QT
STM32的IAP跳转相关bug经历
[PTA--利用队列解决猴子选大王问题】
什么气传导蓝牙耳机好、配置比较高的气传导耳机推荐
气导贴耳式耳机推荐、不需要佩戴入耳的气传导耳机
SSAO By Computer Shader(二)
[untitled]
MFC uses the console to print program information
【二叉树基础知识】
QT batch operation control and set signal slot
【实现简易版扫雷小游戏】
做气传导耳机最好的是哪家、最好的气传导耳机盘点
OJ 1253 点菜问题
OJ 1131 美丽数
微信小程序自定义编译模式
气传导耳机哪个品牌比较好、这四款不要错过
ZOJ Problem 1005 jugs
开放式耳机有哪些、四款音质超好的气传导耳机推荐
【学习笔记】编码能力









