ou 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>2 时f(n) = f(n-1) + f(n-2) f(1) = 1; f(2) = 2;
class Solution { public: int climbStairs(int n) { // Start typing your C/C++ solution below // DO NOT write int main() function if(n <= 2) return n; int f1 = 1, f2 = 2, res = 0; for(int i = 3; i <= n; ++i){ res = f1 + f2; f1 = f2; f2 = res; } return res; } };