N个台阶上法-从递归到迭代

有n步台阶,一次只能上1步或者2步,共有多少种走法?

法一:递归

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    System.out.println(upStep(40));
    long end = System.currentTimeMillis();
    System.out.println(end - start);
}
public static int upStep(int n) {
    if(n ==1 || n == 2) return n;
    else return upStep(n-1) + upStep(n-2);
}
//输出:
165580141
653

改进一下,以为状态转移为f(n) = f(n-1) +f(n-2),递归没有复用之前的结果,每次都从n-k递归到1、2,浪费了性能,

public static void main(String[] args) {
    long start = System.currentTimeMillis();
    System.out.println(upStep(40));
    long end = System.currentTimeMillis();
    System.out.println(end - start);
}
public static int upStep(int n) {
    if(n ==1 || n == 2) return n;
    //初始化,sum为f(n),one为f(n-1),two为f(n-2)
    int one = 2;
    int two = 1;
    int sum = 0;
    for(int i = 3;i <= n;i ++) {
        //f(n) = f(n-1) +f(n-2)
        sum = one + two;
        //f(n-2) = f(n-1),台阶++,状态也需要升级
        two = one;
        //f(n-1) = f(n),升级
        one = sum;
    }
    return sum;
}
//输出:
165580141
1

提升明显

传送门:https://www.bilibili.com/video/BV1nJ411M7ZJ?p=5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值