登阶问题算法

问题描述:假设一个人要登上n阶的地方,他每次登1阶或2阶,问有多少种登法?

//f(n) = f(n-1) + f(n-2)
public class Test {
    public long f(int n){
        long result = 0l;
        if(n == 1 || n == 0 ){
            result = 1;
        }
        else if(n > 1){
            result = f(n-1) + f(n-2);
        }
        return result;
    }
    public static void main(String[] args) {
        Test t = new Test();
        System.out.println("this result:" + t.f(20));
    }
}

测试结果:

Connected to the target VM, address: '127.0.0.1:51417', transport: 'socket'
this result:1346269
Disconnected from the target VM, address: '127.0.0.1:51417', transport: 'socket'

Process finished with exit code 0

问题描述:假设一个人要登上n阶的地方,他每次可登1阶,2阶,...,m阶,问有多少种登法?

public class SuperTest {
    //最大登阶步数,登阶步数为1,2,...,maxStepNumber
    private int maxStepNumber;
    public SuperTest(int maxStepNumber) {
        this.maxStepNumber = maxStepNumber;
    }
    public long f(int n){
        long result = 0l;
        if(n == 0 || n == 1){
            return 1;
        }
        //当n <= maxStepNumber时,f(n) = f(n-1) + f(n-2) +...+ f(0);
        else if(n <= maxStepNumber){
            for(int i = 1; i <= n; i++){
                result = result + f(n - i);
            }
        }
        //当n > maxStepNumber时,f(n) = f(n-1) + f(n-2) +...+ f(n-maxStepNumber);
        else if(n > maxStepNumber){
            for(int i = 1; i <= maxStepNumber; i++){
                result = result + f(n - i);
            }
        }
        return result;
    }

    public static void main(String[] args) {
        SuperTest t =new SuperTest(2);
        System.out.println("this result:" + t.f(30));
    }
}

(30,2)测试结果:

Connected to the target VM, address: '127.0.0.1:51260', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:51260', transport: 'socket'
this result:1346269

Process finished with exit code 0

 (30,5)测试结果:

Connected to the target VM, address: '127.0.0.1:51292', transport: 'socket'
Disconnected from the target VM, address: '127.0.0.1:51292', transport: 'socket'
this result:345052351

Process finished with exit code 0

 总结:第二种方案是一个通用方案,对于简单的登阶问题像第一种情况也可以用排列组合编码解决

猜你喜欢

转载自www.cnblogs.com/myxcf/p/10131425.html