当前位置:网站首页>Dynamic planning -- multi-step stair climbing (advanced version of stair climbing)
Dynamic planning -- multi-step stair climbing (advanced version of stair climbing)
2022-07-28 06:39:00 【Step by step b】
Step up the stairs
Title Description 1
Suppose you're climbing the stairs . need n You can reach the top of the building .
Every time you climb 1 or 2 A stair ,3 A stair …, until m A stair . How many different ways can you climb to the top of the building ?
Be careful : Given n Is a positive integer .
Example 1:
Input : 2
Output : 2
explain : There are two ways to climb to the top .
1 rank + 1 rank
2 rank
Example 2:
Input : 3
Output : 3
explain : There are three ways to climb to the top .
1 rank + 1 rank + 1 rank
1 rank + 2 rank
2 rank + 1 rank
1 rank ,2 rank ,… m Order is the object , The roof is the backpack .
Each step can be reused , For example, I jumped 1 rank , You can continue to jump 1 rank .
There are several ways to jump to the top of a building. In fact, there are several ways to fill a backpack .
It's a complete knapsack problem
analysis :
1. determine dp Array meaning : Climb to i There are... On the top of the building with steps dp[i] Methods
2. Determine the recurrence formula : The recurrence formula of several methods to solve knapsack problem is generally dp[i] += dp[i-nums[i]];
The recurrence formula of this problem is :dp[i] += dp[i-j]
3. initialization dp Array : There is a recursive formula that shows dp[0] = 1 because dp[0] It is the basis of all numerical values in the recursive process , If dp[0] by 0, Then other values are 0
4. Establish traversal order : This question is about permutation , That is, the outer layer traverses the knapsack , Inner traversal item . If it is a combination problem , Then the outer layer is traversal items , The inner layer is traversal knapsack
5. Give an example to deduce dp Array
Code
#include<iostream>
#include<vector>
using namespace std;` Insert a code chip here `
class Solution{
public:
int climbStairs(int n, int m) {
vector<int> dp(n+1);
dp[0] = 1;
for (int i = 1; i <= n; i++) {
// Traverse the backpack
for (int j = 1; j <= m; j++) {
// Traverse the items
if (i-j >= 0) dp[i] += dp[i-j];
}
}
return dp[n];
}
};
int main() {
int n, m;
cin>>n>>m;
Solution Q;
cout<<Q.climbStairs(n,m);
}
边栏推荐
猜你喜欢
随机推荐
C语言的编译和预处理
AQS之countDownLatch源码分析
Explain the installation of MSDN 2015 and precautions
QT solves the problem of rebuilding UI files every time they are modified
Solve the problem that the memory occupation is higher than that of the application process
Battle plague Cup -- my account book
Valgrind tool
什么气传导蓝牙耳机好、配置比较高的气传导耳机推荐
开放式耳机推荐哪款最好、性价比最高的开放式耳机
OJ 1018 报数游戏
关于时间复杂度,你不知道的都在这里
【C笔记】数据类型及存储
Leetcode 刷题日记 剑指 Offer II 048. 序列化与反序列化二叉树
Leetcode 刷题日记 剑指 Offer II 050. 向下的路径节点之和
当前学习进度
气传导耳机哪个好、性价比最高的气传导耳机推荐
[c语言]简易通讯录的实现
Antenna effect solution
Leetcode 刷题日记 剑指 Offer II 047. 二叉树剪枝
C语言的文件操作









![[PTA----输出全排列]](/img/66/d1699cd55fa5ff4a55e3e150d02c1b.png)