n个台阶,每次可以走1或2阶,问有多少种方式

循环和递归方式实现及比较

package com.example.demo.paixu;

import java.math.BigInteger;
import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

/**
 * @Description TODO
 * @Date 2020/4/8 21:16
 * @Created by zengq
 */
public class Demo {
    public static void main(String[] args) {
        /*getN();*/

        /*long stepNumber = getStepNumber(8);
        System.out.println(stepNumber);*/

    }

    /**
     * 排雷组合-循环方式
     * 循环相对来说效率比递归要号
     * 原因是递归是方法不断调用自身,要不断的创造栈,给变量分配空间,出入栈操作,必然导致效率问题。
     * 当然递归解决的问题要比循环多,且简介方便验证。
     * 选择循环还是递归方式看具体的场景吧
     *
     */
    private static void getN() {
        Set set = new HashSet();
        Scanner in = new Scanner(System.in);
        long n = in.nextLong();
        long sum = 1;
        long score = n/2;
        for(long i = 1; i<=score; i++){
            BigInteger n_j = BigInteger.valueOf(n-i);
            BigInteger j = BigInteger.valueOf(i);
            BigInteger n_2j = BigInteger.valueOf(n-i-i);
            sum = sum +fun(n_j).divide(fun(j).multiply(fun(n_2j))).longValue();
        }
        System.out.println(sum);
    }

    //求n的阶乘方法
    public  static BigInteger fun(BigInteger n){
        BigInteger x = new BigInteger("1");

        for(long i = 1; i<=n.longValue(); i++){
            x = x.multiply(new BigInteger(String.valueOf(i)));
        }

        return x;
    }


    /**
     * 分治-递归实现   注意递归的结束条件
     * @param n
     * @return
     */
    public static long getStepNumber(int n)  {

        if (0 > n) {
            return 0;
        }

        if (n == 1) {
            return 1;
        }

        if (n == 2) {
            return 2;
        }


        if (n > 2) {
            return getStepNumber(n - 1) + getStepNumber(n - 2);
        }
        return 0;
    }

}

你可能感兴趣的:(面试题或算法)