当前位置:网站首页>70. Stair Climbing Advanced Edition
70. Stair Climbing Advanced Edition
2022-08-10 00:33:00 【empty__barrel】
Refer to Code Caprice
70. Climbing stairs
This question is a partial modification of the original question:
Let's say you're climbing stairs.You need n steps to get to the top of the building.
Each time you can climb 1 or 2…n steps.How many different ways can you get to the top of a building?
dp array meaning:
dp[i]: There are dp[i] ways to climb to the top of the building with i steps.
Recursive formula:
dp[i] += dp[i -j];
Initialization:
dp[0] must be 1, dp[0] is the basis of all values in the recursion, if dp[0] is 0, other values are 0.
Traversal order:
This is a complete knapsack, so it is a sequential traversal. Through analysis, we can see that the sequence in this dp is an arrangement, so pay attention to the order in which the two for loops are nested
If the number of combinations is sought, the outer for loop traverses the items, and the inner for loops through the backpack
If the number of permutations is sought, the outer for loop traverses the backpack, and the inner for loop traverses the items
Convert the title:
One step, one step, two steps, etc., and then the whole process is, how many steps are taken each time and then to the top of the building.
Think of it this way: the number of steps that can be taken is an array, and the value from the array (each element can be taken repeatedly) is the number of steps required to go up to the top of the building.
At this point, it is clear that this is a complete knapsack problem.
class Solution {public:int climbStairs(int n) {vector<int> dp(n + 1, 0);dp[0] = 1;for (int i = 1; i <= n; i++) { // Traverse the backpackfor (int j = 1; j <= m; j++) { // Traverse itemsif (i - j >= 0) dp[span>i] += dp[i - j];}}return dp[n];}};
The m in the code means that you can climb 1~m steps, and changing m to 2 in the code is the code for this question 70. Climbing stairs can be AC.
边栏推荐
猜你喜欢
随机推荐
继承关系下构造方法的访问特点
Redis集群
Transfer Learning & Kemin Initialization
setter与getter访问器属性——数据驱动显示
Bi Sheng Compiler Optimization: Lazy Code Motion
Qt message mechanism and events
深度学习100例 —— 循环神经网络(RNN)实现股票预测
【云原生】一文讲透Kubevela addon如何添加腾讯Crane
Leetcode 236. 二叉树的最近公共祖先
leetcode 20. Valid Parentheses 有效的括号(中等)
金仓数据库 KingbaseGIS 使用手册(6.6. 几何对象校验函数、6.7. 空间参考系函数)
tiup cluster start
浅析量股票化交易的发展现状
1018.值周
Filament-Material 绘制基本图形
Miscellaneous talk - the sorrow of programmers
三:OpenCV图片颜色通道数据转换
【哲理】事教人
数字与中文大写数字互转(5千万亿亿亿亿以上的数字也支持转换)
联盟链技术应用的难点