题目描述
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?
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 == 0)
return 1;
if(n == 1)
return 1;
else
return (climbStairs(n-1) + climbStairs(n-2));
}
};
一维动态规划
class Solution {
public:
int climbStairs(int n) {
int n1 = 1;
int n2 = 1;
if(n == 0)
return 1;
if(n == 1)
return 1;
else
{
for(int i = 1;i < n;i++)
{
int tmp = n2;
n2 = n1+n2;
n1 = tmp;
}
}
return n2;
}
};