Title:
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?
思路:f(n)表示到n需要的种数。考虑下到n的几种可能。实际就是两种,一种是跳一步,另一种是跳两步。所以到n需要的种数是f(n) = f(n-1)+f(n-2),所以就是斐波那契数列,代码是其非递归写法。
class Solution{ public: int climbStairs(int n){ int *v = new int [n]; v[0] = 1; v[1] = 2; for (int i = 2; i < n ; i++){ v[i] = v[i-1] + v[i-2]; } return v[n-1]; } };