https://leetcode.com/problems/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?
1)递归: 超时
class Solution { public: int climbStairs(int n) { if (n==1) return 1; if(n==2) return 2; return climbStairs(n-1)+climbStairs(n-2); } };
2)非递归, 避免嵌套调用
递推公式
a_n=a_{n-1}+a_{n-2}.
a_1=1, a_2=2.
问题:给定n求a_n。其实就是斐波那契数列。
AC代码:
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 if (n==1) 5 return 1; 6 if (n==2) 7 return 2; 8 int t=2,x=1,y=2,z; 9 while(t!=n){ 10 t++; 11 z=x+y; 12 x=y; 13 y=z; 14 } 15 return z; 16 } 17 };