楼梯走法

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

}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容