0
点赞
收藏
分享

微信扫一扫

[面试]算法题走楼梯

千妈小语 2022-02-09 阅读 50

题目

假设楼梯有n层高,每次只能走一步或者两步,求有多少种走法
思路一:
计算过程就是方法,层数作为参数,声明方法f(x)。根据情况分析
一层:1种方法 f(1) = 1
二层:2种方法f(2) = 2
三层:先到达f(1),然后从f(1)跨两步,或者先到达f(2),从f(2)跨一步,f(3) = f(1) + f(2)
四层:先到达f(2),然后从f(2)跨两步,或者先到达f(3),从f(3)跨一步,f(4) = f(2) + f(3)
n层:先到达f(n-2),然后从f(n-2)跨两步,或者先到达f(n-1),从f(n-1)跨一步,f(n) = f(n-2) + f(n-1)
通俗点说,每走到第n层,分两种情况,要么是从第n-1层走一步上来的,要么就是从第n-2层走两步上来的。那么第n层的全部走法就是n-1层全部走法加上n-2层全部走法
使用递归解决,代码如下:

public class Demo4 {

    public static int f(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        return f(n - 2) + f(n - 1);
    }

    @Test
    public void test() {
        long start = System.currentTimeMillis();
        int f = f(40);
        System.out.println("总共走法:" + f);
        long end = System.currentTimeMillis();
        System.out.println(String.format("用时:%sms",  (end - start)));
    }
}

运行结果

总共走法:165580141
用时:321ms

递归有大量重复运算,占用资源高,效率较低

思路二:
在思路一的基础上进行改善,已知第n层的走法就是n-1层加上n-2层的总走法。那么使用循环,并且记录n-1层和n-2层的总走法即可,代码如下:

public class Demo4 {

    public static int f1(int n) {
        if (n == 1 || n == 2) {
            return n;
        }
        // 假设从第三层开始
        int n1 = 2; // n-1层总走法
        int n2 = 1; // n-2层总走法
        // 开始计算
        int sum = 0; // 记录总走法
        for(int i =3; i<=n;i++) {
            sum = n1 + n2;
            n2 = n1; // 本层n-1的走法就是下一层n-2的走法
            n1 = sum; // 本层n全部走法就是下一层n-1的走法
        }
        return sum;
    }

    @Test
    public void test() {
        long start = System.currentTimeMillis();
        int f = f1(40);
        System.out.println("总共走法:" + f);
        long end = System.currentTimeMillis();
        System.out.println(String.format("用时:%sms",  (end - start)));
    }
}

运行结果

总共走法:165580141
用时:0ms

可以看出,效率比递归高的多

举报

相关推荐

0 条评论