leetcode 70

爬楼梯

Posted by Static on June 13, 2020

题目链接:https://leetcode-cn.com/problems/climbing-stairs/

题目描述


分析

f(x)=f(x-1)+f(x-2) (x>2),当前数字=前两个数字之和

1. 循环

2. 递归


代码实现

public enum Q70 {

    instance;

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

    public int climbStairs1(int n) {
        if(n==0)return 0;
        if(n<=2) return n;
        int a=0,b=1,s=0;
        for(int i=1;i<=n;i++){
            s=a+b;
            a=b;
            b=s;
        }
        return s;
    }

    public static void main(String[] args) {
        // 377
        System.out.println(Q70.instance.climbStairs(13));
        System.out.println(Q70.instance.climbStairs1(13));
    }
}