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

【Leetcode】Climbing Stairs

2017-11-08 21:29 260 查看
题目:

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级阶梯。 

每次你可以选择爬一级或者二级。在多少不同的方式去到达顶部?

分析: 

当n=1,无疑只有一种方式,s=1。 

n=2,s=2。 

n=3,s=3。 

n=4,s=5。 

我们发现这个实际是一个斐波那契数列。第一反应是递归实现,f(n)=f(n-1)+f(n-2),但是递归实现,有多次重复计算,比如在计算f(n-1)时,需要使用f(n-2)+f(n-3),但是这个时候另一个递归调用已经去算了f(n-2),相当于f(n-2)被计算了2次,这种重复计算的情况普遍存在,将会浪费大量计算时间。很自然的想到反过来操作,递归是从目标算到基础值,而我们可以采用迭代从基础值1,2累加上去。
Java版本:

class Solution {
public int climbStairs(int n) {

//递归
// if(n == 1 || n ==2){
//     return n;
// }else{
//     return climbStairs(n - 1) + climbStairs(n - 2);
// }

//迭代
// if(n == 1 || n ==2){
//     return n;
// }
// int n1=1;int n2=2;
// for(int i=3;i<=n;i++){
//     int temp=n1+n2;
//     n1=n2;
//     n2=temp;
// }
// return n2;
int a =1, b = 1;
for(int i = 1; i <= n; i++){
a = b;
b = a + b;
}
return a;
}
}


此处若用递归,在Leetcode上出现“ Time Limit Exceeded”

Python版本:

def climbStairs(self, n):
a = b = 1
for _ in range(n):
a, b = b, a + b
return a


C++版本:

class Solution {
public:
int climbStairs(int n) {

int climbStairs(int n) {
int a = 1, b = 1;
while (n--)
a = (b += a) - a;
return a;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: