【LeetCode】70 - Climbing Stairs

时间:2023-03-10 02:52:41
【LeetCode】70 - 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?

Hide Tags: Dynamic Programming
Solution:一个台阶的方法次数为1次,两个台阶的方法次数为2个。n个台阶的方法可以理解成上n-2个台阶,然后2步直接上最后一步;或者上n-1个台阶,再单独上一步
 int climbStairs(int n) {    //Runtime:0ms
int a=,b=;
if(n==)return a;
if(n==)return b;
int c=;
for(int i=;i<=n;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
int climbStairs2(int n){ ////Runtime:0ms
if(n <= )return n;
int* step = new int[n];
step[] = ;
step[] = ;
for(int i = ; i < n; i++)step[i] = step[i-] + step[i-];
return step[n-];
}