zoukankan      html  css  js  c++  java
  • 70. Climbing Stairs

    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;
    }
    }

  • 相关阅读:
    CDS视图篇 1
    SAP S/4 HANA与SAP Business Suite/R3(ECC)的区别
    SAP R3和SAP Business One的区别
    REUSE_ALV_POPUP_TO_SELECT使用技巧
    ALV显示金额字段值扩大100倍
    取汇率
    货币转换函数:CURRENCY_CONVERTING_FACTOR
    SUBMIT标准程序取ALV数据
    未清SO关闭处理
    [转载]树、森林和二叉树的转换
  • 原文地址:https://www.cnblogs.com/mafang/p/8676718.html
Copyright © 2011-2022 走看看