原题
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:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
翻译
你正在爬楼梯. 需要n步才能达到顶峰.
每次你能爬1或2阶. 你有多少种不同的方法爬到顶。
注意: n是一个正数
例 1:
输入: 2
输出: 2
说明: 有两种方法爬到顶端.
1. 1 步+ 1 步
2. 2 步
例 2:
输入: 3
输出: 3
说明: 有三种方法爬到顶端.
1. 1 步+ 1 步+ 1 步
2. 1 步+ 2 步
3. 2 步+ 1 步
程序
int climbStairs(int n){
if(n==0||n==1||n==2)return n;
int temp1=1,temp2=2;
int temp = 0;
for(int i=2;i<n;i++)
{
temp=temp2;
temp2 = temp1 + temp2;
temp1 = temp;
}
return temp2;
}
总结
- 动态规划问题,本问题与斐波那契是同一类问题