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?

Note: Given n will be a positive integer.

现在你正在上楼,到达顶部需要走n个台阶。

每次你可以跨1或2个台阶。到达顶部你又多少种不同的方式呢?

注意:n为正整数。

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)个台阶所有可能的走的方式;若最后一步走两个台阶,那么可能的方式为(n-2)个台阶所有可能的走的方式.所以对于n个台阶来说,可能的走的方式为(n-1)和(n-2)的方式相加。

public int climbStairs(int n) {
if(n<=2)
return n;
return(climbStairs(n-1)+climbStairs(n-2));
}

该程序时间超了,查了一下递归非递归转化,将算法转化为非递归

class Solution {
  public int climbStairs(int n) {
    if (n <= 2)
      return n;
    int pre1 = 2, pre2 = 1,temp=0;
    for (int i = 3; i < n; i++) {
      temp=pre2;
      pre2 = pre1;
      pre1 += temp;
    }

    return pre1 + pre2;
}
}

posted @ 2018-03-30 16:01  同销万古愁  阅读(136)  评论(0编辑  收藏  举报