- Climbing Stairs II
A child is running up a staircase with n steps, and can hop either 1 step, 2 steps, or 3 steps at a time. Implement a method to count how many possible ways the child can run up the stairs.
Example
n=3
1+1+1=2+1=1+2=3=3
return 4
解法: 典型DP。
记得dp数组要初始化为1。
class Solution {
public:
/**
* @param n: An integer
* @return: An Integer
*/
int climbStairs2(int n) {
vector<int> dp(n + 1, 1);
dp[2] = 2;
for (int i = 3; i <= n; ++i) {
dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3];
}
return dp[n];
}
};
本文探讨了经典的爬楼梯问题,通过动态规划的方法计算孩子以1、2或3步方式爬上n阶楼梯的不同路径数量。展示了如何使用C++实现这一算法,包括初始化dp数组并迭代计算直到达到目标步骤。
488

被折叠的 条评论
为什么被折叠?



