LeetCode题解:Climbing Stairs

来源:互联网 发布:危机公关 知乎 编辑:程序博客网 时间:2024/05/22 07:56

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?

题意:每次上楼梯的步数只能为1或2,求上n层楼梯的办法数

解决思路:

动态规划,状态转移方程:f(n) = f(n - 1) + f(n - 2) (n > 2),f(0) = 0,f(1) = 1,f(2) = 2.
斐波那契,随便选个n做例子算办法数就会发现和斐波那契数列是一样的(状态转移方程就一样),所以可以直接利用这一点实现,不需要O(n)
的空间来完成动态规划
代码:

动态规划:

public class Solution {    public int climbStairs(int n) {        if(n == 0 || n == 1 || n == 2){            return n;        }        int[] mem = new int[n];        mem[0] = 1;        mem[1] = 2;        for(int i = 2; i < n; i++){            mem[i] = mem[i-1] + mem[i-2];        }        return mem[n-1];    }}

斐波那契:

public class Solution {    public int climbStairs(int n) {        if(n < 0){            return 0;        }        if(n < 3){            return n;        }        int result = 0;        int oneStep = 1;        int twoStep = 1;        for(int i = 2;i <= n;i++){            result = oneStep + twoStep;            twoStep = oneStep;            oneStep = result;        }        return result;    }}
0 0
原创粉丝点击