Climbing Stairs

来源:互联网 发布:兰尼斯特有债必偿 知乎 编辑:程序博客网 时间:2024/06/06 14:09

Solution 1: 递归,超时=。=

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

Solution 2: 使用动态规划,从前向后计算,减少重复计算次数。过程类似于斐波那契数列,只不过是从1,2开始的

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