题目描述:
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.
Example 1:
Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps
Example 2:
1 Input: 3 2 Output: 3 3 Explanation: There are three ways to climb to the top. 4 5 1. 1 step + 1 step + 1 step 6 2. 1 step + 2 steps 7 3. 2 steps + 1 step
解题思路:
这道题由题意可以得到一个递推公式an=a(n-1)+a(n-2),我一开始是用递归来写,可能是因为嵌套太多层的原因,超过了时限,然后换成了循环。
代码:
1 class Solution { 2 public: 3 int climbStairs(int n) { 4 int pre=1; 5 int cur=1; 6 for(int i=1;i<n;i++){ 7 int t=cur; 8 cur=pre+cur; 9 pre=t; 10 } 11 return cur; 12 } 13 };