您的位置:首页 > 大数据 > 人工智能

【LeetCode】70 - Climbing Stairs

2015-07-26 22:26 465 查看
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=1,b=2;
if(n==1)return a;
if(n==2)return b;
int c=0;
for(int i=3;i<=n;i++){
c=a+b;
a=b;
b=c;
}
return c;
}
int climbStairs2(int n){    ////Runtime:0ms
if(n <= 2)return n;
int* step = new int
;
step[0] = 1;
step[1] = 2;
for(int i = 2; i < n; i++)step[i] = step[i-1] + step[i-2];
return step[n-1];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: