70. Climbing Stairs

本文探讨了一个经典的编程面试题——爬楼梯问题,即如何计算以1或2个台阶的方式达到第n个台阶的不同组合数。文章通过递归及非递归两种方法给出了解决方案,并详细解释了其背后的数学原理——斐波那契数列。

 

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?

Note: Given n will be a positive integer.

现在你正在上楼,到达顶部需要走n个台阶。

每次你可以跨1或2个台阶。到达顶部你又多少种不同的方式呢?

注意:n为正整数。

Example 1:

Input: 2
Output:  2
Explanation:  There are two ways to climb to the top.

1. 1 step + 1 step
2. 2 steps

 

Example 2:

Input: 3
Output:  3
Explanation:  There are three ways to climb to the top.

1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

这个题我在招商银行和京东的笔试中见过,印象非常深,所以很快写出了如下递归程序(其实就是斐波那契数列)

原因如下,设有n个台阶,那么只看最后一步怎么走,若最后一步只走一个台阶,那么可能的方式为(n-1)个台阶所有可能的走的方式;若最后一步走两个台阶,那么可能的方式为(n-2)个台阶所有可能的走的方式.所以对于n个台阶来说,可能的走的方式为(n-1)和(n-2)的方式相加。

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

该程序时间超了,查了一下递归非递归转化,将算法转化为非递归

class Solution {
  public int climbStairs(int n) {
    if (n <= 2)
      return n;
    int pre1 = 2, pre2 = 1,temp=0;
    for (int i = 3; i < n; i++) {
      temp=pre2;
      pre2 = pre1;
      pre1 += temp;
    }

    return pre1 + pre2;
}
}

转载于:https://www.cnblogs.com/mafang/p/8676718.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值