70. Climbing Stairs

来源:互联网 发布:梦里花落知多少封面 编辑:程序博客网 时间:2024/06/07 19:30

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?

Subscribe to see which companies asked this question

用迭代也可以做,但是略比直接菲波那切数列算结果要慢。上一级台阶有1种方式,上零级台阶也是1种方式(不动),以此为初始条件。上n节台阶的方式为最后一步走2级和1级两种,所以可以是之前n-2级的全部走法加最后走2级/n-1级的全部走法加最后走1级两种走法。所以f(n)=f(n-1)+f(n-2)

public class Solution {    public int climbStairs(int n) {        int a = 1, b = 2;    int c = 0;        if (n == 1) return a;    if (n == 2) return b;        for (int i = 2; i < n; ++i)    {        c = a + b;        a = b;        b = c;    }        return c;    }}
0 0
原创粉丝点击