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?
本题对应了《剑指offer》上的跳台阶。
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
题目解法
本题是一道很典型的递归题目,根据题目的初始条件可知:
- f(1) = 1;
- f(2) = 2;
- f(n) = f(n-1) + f(n-2) (n > 2)
对于n个台阶时的解释是,最后青蛙可以一次跳一个台阶,则解法是f(n-1);也可以直接跳两个台阶,则解法是f(n-2)。
其实到这里大家可以发现本题和斐波拉切数列的思路相同,不同点仅仅在于初始条件,因此可以使用递归得到结果。然而本题的递归过程中会涉及到太多的重复计算。因为在计算f(n)的时候需要计算f(n-1)和f(n-2),而在计算f(n-1)时本身也是需要计算f(n-2)的。所以还是不采用递归的方式,使用两个变量分别表示为f(n-1)和f(n-2)并更新这两个变量,从而得到最终结果。
下面给出递归和非递归两种解法:
1 #include<stdio.h> 2 int fRecur(int n) 3 { 4 if (n < 3) 5 { 6 return n; 7 } 8 return fRecur(n - 1) + fRecur(n - 2); 9 } 10 11 12 int fn(int n) 13 { 14 int a = 1, b = 2; 15 int i = 2; 16 if (n < 3) 17 { 18 return n; 19 } 20 while (i < n) 21 { 22 a = a + b; 23 b = a + b; 24 i += 2; 25 } 26 27 return n == i ? b : a; 28 } 29 30 int main(void) 31 { 32 int n; 33 scanf("%d", &n); 34 printf("rs:%d\n", fRecur(n)); 35 printf("rs:%d\n", fn(n)); 36 }
「Talk is cheap. Show me the code」

浙公网安备 33010602011771号