70. Climbing Stairs
题目:
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
代码如下:
方案一:
class Solution {
public:
int climbStairs(int n) {
if (n == 0 || n == 1 || n == 2) return n;
int ans = climbStairs(n - 1) + climbStairs(n - 2);
return ans;
}
};
太过费时,可以用数组把每次所得结果存起来,避免了重复计算。
方案二:
class Solution {
public:
int climbStairs(int n) {
if (n == 0 || n == 1 || n == 2) return n;
int ans[1000];
ans[1] = 1;
ans[2] = 2;
for (int i = 3; i <= n; i++)
ans[i] = ans[i - 1] + ans[i - 2];
return ans[n];
}
};
解题思路:
本题实际上是一个斐波那契数列。
如果n=0,则路径数应为零。
如果n=1,那么只有爬楼梯的方法。
如果n=2,那么有两种爬楼梯的方法。要么一次一步,要么一次两步。
对于每n层楼梯,只需考虑,若剩下两步可走,或剩下一步,采用递归的思路,把问题分解为多个子问题,即可。