ProgrammerAndroid开发经验谈Android开发

楼梯走法

2019-07-26  本文已影响3人  崔鹏宇

Github

public class 楼梯走法 {
    private static int i = 0;

    public static void main(String[] args) {
        calc("", 4);
        System.out.println("共有几种 = [" + i + "]");
    }

    //上楼梯每次只需一步或者两步,有多少走法
    public static void calc(String log, int num) {
        /**
         *  相减     log值
         *  4-1=3      1
         *  --------------
         *  3-1=2      1、1
         *  2-1=1      1、1、1
         *  1-1=0      1、1、1、1
         *  --------------
         *  3-2=1      1、2
         *  1-1=0      1、2、1
         *  --------------
         *  3-1=2      1、1
         *  2-2=0      1、1、2
         *  -----------------
         *
         *  4-2=2       2
         *  -----------------
         *  2-1=1       2、1
         *  1-1=0       2、1、1
         *  -----------------
         *  2-2=0       2、2
         *
         */
        if (num == 0) {
            i++;
            System.out.println(log);
            return;
        } else if (num == 1) {
            i++;
            System.out.println(log + "1");
            return;
        }
        calc(log + "1  ", num - 1);
        calc(log + "2  ", num - 2);
    }

}
上一篇 下一篇

猜你喜欢

热点阅读