每日一练_96(2021.9.13) 爬楼梯(leetcode)。

前几天做了挺多的回溯的题,我就用回溯的方法做了这道题,结果提交的时候超出内存限制了。(我在最底下粘贴出了官方的一种官方答案。)

回溯:

import java.util.ArrayList;
import java.util.List;

class stairs{
    public int climbStairs(int n) {
        return permutation(n).size();
    }
    public  List<List<Integer>> permutation(int n){
        List<List<Integer>> res = new ArrayList<>();
        if(n==0) return res;
        List<Integer> path = new ArrayList<>();
        int nums[] = new int[] {1,2};
        dfs(nums,n,0,path,res);
        return res;
    }
    public void dfs(int nums[],int sum,int depth,List<Integer> path,List<List<Integer>> res) {
        if(depth>sum) {
            return;
        }
        if(depth==sum) {
            res.add(new ArrayList<>(path));
            return;
        }
        for(int i=0;i<2;i++) {
            depth = depth+nums[i];
            path.add(nums[i]);
            dfs(nums,sum,depth,path,res);
            path.remove(path.size()-1);
            depth = depth-nums[i];
        }
    }
}

public class ClimbingStairs {
    public static void main(String args[]) {
        stairs hah = new stairs();
        System.out.println(hah.permutation(4));
        System.out.println(hah.climbStairs(4));
    }
}
测试结果:

[[1, 1, 1, 1], [1, 1, 2], [1, 2, 1], [2, 1, 1], [2, 2]]
5
 

官方答案:

作者:LeetCode-Solution
链接:https://leetcode-cn.com/problems/climbing-stairs/solution/pa-lou-ti-by-leetcode-solution/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

官方用了一种规律:

f(x)=f(x−1)+f(x−2)
f(0)=1
f(1) = 1
f(2) = 2,f(3) = 3,f(4) = 5,……

class Solution {
    public int climbStairs(int n) {
        int p = 0, q = 0, r = 1;
        for (int i = 1; i <= n; ++i) {
            p = q; 
            q = r; 
            r = p + q;
        }
        return r;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是壮壮没错了丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值