Leet Code OJ 70. Climbing Stairs(爬楼梯问题)

来源:互联网 发布:删除mac账号 编辑:程序博客网 时间:2024/06/06 17:58

题目

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?

这是一个爬楼梯问题,给定楼梯层数n,每一步只能走1层或者2层,问上到楼梯顶有多少种方式?

分析

这是一个动态规划的问题:(斐波那契数列问题)
n:方式
1:1
2:2
3:3

f(n)=f(n-1)+f(n-2)

解题

我想到有两种方式
第一种是递归,代码很简单,但是这样Leetcode会超时

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

第二种是非递归:
上面递归的方式会导致有很多重复子问题,例如当n=4的时候,此时需要求n=3和n=2的情况,然后求n=3,又需要求n=1 和 n=2的情况,此时已经求了两个n=2的情况了。所以这就是重复的关键点,也是耗时的关键点
因此用动态规划的思想,自底向上求解:

    public int climbStairs(int n) {        if(n <= 2) return n;        int[] step = new int[n+1];        step[1] = 1;        step[2] = 2;        for(int i = 3; i <= n; i++){            step[i] = step[i-1] + step[i-2];        }        return step[n];    }
0 0
原创粉丝点击