zoukankan      html  css  js  c++  java
  • 【面试题】N阶台阶,每次走一步或两步,计算共有多少种走法,并将每种走法打印出来。

    题目重述:有N阶台阶,每次可以走一步也可以走两步,计算共有多少种走法,并将每种走法打印出来。

    以下解法主要利用了二叉树和递归的解题思路。

    public class StepCompute {
    	private static int total=0; // 计
        private static void printSteps(String preSteps, int leftSteps) {
            if(preSteps == null)
                preSteps = "";
            if(leftSteps < 0) {
                System.out.println("台阶数不能小于0");
            }
            if(leftSteps == 1) {
                System.out.println("走法:"+preSteps + " 1");
                total++;
                return;
            }
            else if(leftSteps == 0) {
                System.out.println("走法:"+preSteps);
                total++;
                return;
            }
            for(int i = 1; i <= 2; i++) {
                printSteps(preSteps + " " + i, leftSteps - i);
            }
        }
        public static void main(String[] args) {
            printSteps("", 4);
            System.out.println("共"+total+"种走法");
        }
    }
    
    

    打印效果:

    走法: 1 1 1 1
    走法: 1 1 2
    走法: 1 2 1
    走法: 2 1 1
    走法: 2 2
    共5种走法
    

    也可以从前几阶台阶推算一下,1-5阶台阶对应走法分别是1、2、3、5、8种走法,很像斐波那契数列,如果只是计算共有多少种走法的话,那我们可以利用斐波那契数列法来计算,代码如下:

    public class StepCompute {
        public static int computeStep(int step){
            if(step == 0){
                return 0;
            }
            if(step == 1){
                return 1;
            }
            if(step == 2){
                return 2;
            }
            return computeStep(step - 1) + computeStep(step - 2);
        }
         public static void main(String[] args) {
            System.out.println(computeStep(4));
        }
    }
    
  • 相关阅读:
    Java-判断一个数是不是素数
    Sublime快捷键
    python
    全排列
    python
    python
    OpenCV 实现图像结构相似度算法 (SSIM 算法)
    C++
    C++
    NFA 转 DFA
  • 原文地址:https://www.cnblogs.com/xmm2017/p/13943878.html
Copyright © 2011-2022 走看看