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

LintCode Climbing Stairs 爬楼梯

2015-07-11 22:05 627 查看
中文描述:

假设你正在爬楼梯,需要n步你才能到达顶部。但每次你只能爬一步或者两步,你能有多少种不同的方法爬到楼顶部?

样例

比如n=3,1+1+1=1+2=2+1=3,共有3中不同的方法

返回 3

English Version:

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?

Example

Given an example n=3 , 1+1+1=2+1=1+2=3

return 3

public class Solution {
/**
* @param n: An integer
* @return: An integer
*/
//法一:动归
public int climbStairs(int n) {
int one = 0;
int two = 1;
while(n>0)  {
two=one+two;
one=two-one;
n--;
}
return two;
}

//法二:递归迭代,超时
public int climbStairs(int n) {
if(n==1)return 1;
if(n==2)return 2;
return climbStairs(n-1)+climbStairs(n-2);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: