leetcode 70. Climbing Stairs

27 篇文章 0 订阅
25 篇文章 0 订阅

题目内容
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和n-2两种情况。而完成n步的情况就为,F(n)种,可以推出F(n)=F(n-1)+F(n-2)种。
所以不难发现,递推关系,

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

是斐波那契数列。。。。如果发现不了你就记住!!!这个式子是斐波那契数列.

所以解题有两种方式常用的方式,递归,和迭代。
递归一般因为占用空间太大而被抛弃。在leetcode上跑了一下,大概能计算到n=44.
迭代的话,是个正向的过程,直接从n=1开始加,加到n,时间复杂度为 O(n)。

递归

public class Solution {
    public int climbStairs(int n) {

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

迭代

public class Solution {
    public int climbStairs(int n) {
        int one=0;
        int two=1;
        int sum=0;

        for(int i=0;i<n;i++)
        {
            sum=one+two;
            one =two;
            two=sum;
        }
        return sum;

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值