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.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
题解:
这也是一道动态规划的题目,但仔细一看其实它的本质就是斐波那契数列。因为每次只能走一步或者两步,也就是说如果一共有n个台阶的话,就相当于是在n-1个台阶的基础上再走一步,或者在n-2个台阶的基础上走两步,所以有n个台阶的方法总数就是有n-2个台阶和有n-1个台阶的方法之和。刚开始用了递归的斐波那契算法,运行结果是正确的但是超时了,所以后面就改成了用数组实现斐波那契。
代码:
class Solution {
public:
int climbStairs(int n) {
int * fib = new int[n + 1];
fib[0] = 0;
fib[1] = 1;
fib[2] = 2;
for (int i = 3; i <= n; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
return fib[n];
}
};