关于递归、回溯算法的思考

关于递归、回溯算法的思考

一堆废话:记得第一次看递归的时候,看例子都满脑子浆糊。在LeetCode上做到combination sum, subsets系列的问题,从刚开始时的毫无思路,到现在知道要用递归并且有回溯的模板,但就是写不出来。学而不思则罔,所以现在打算写一篇小文章来总结、思考。

用自己喜欢的方式解读递归

一个例子:

  1. Java代码如下

    public class Recursion {
    	public static void main (String [] args) {
    		System.out.print("吓得我抱起了");
    		rec(3);
    	}
    	public static void rec (int numOfBao) {
    		if(numOfBao == 0) {
    			System.out.print("我的小鲤鱼");
    			return;
    		}
    		System.out.print("抱着");
    		rec(numOfBao - 1);
    		System.out.print("的我");
    	}
    }
    

2.Output如图所示。(不记得从哪里保存的这个图和idea了,非原创。) List item

LeetCode上经典递归题

很多,Path Sum系列,Combination Sum全家桶,Permutations…
在这里就举例LC的Permutation。
https://leetcode.com/submissions/detail/205163601/
题意:给定一个没有重复数字的数组,要你return改数组所有数字的排序方式。

Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

通过观察可以发现,每个List的长度都跟input的list长度一样。(都是3), 所以这就是个很明显的base case。

class Solution {
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> res = new ArrayList <>();
        helper(res, new ArrayList<Integer>(), nums);
        return res;
    }
    
    public void helper(List<List<Integer>> res, ArrayList<Integer> temp, int [] nums){
        if (temp.size() == nums.length){ //base case! 
            res.add(new ArrayList(temp));
            return;
        }
        for(int n : nums){
            if(!temp.contains(n)){
                temp.add(n);
                helper(res, temp, nums);
                temp.remove(temp.size()-1);
            }
        }
    }
}

对于每个在nums数组中的整数n,我们首先判断它在有可能加入res的数组中有没有出现过。如果没有出现,则加入临时list中。然后进行对input数组中下一个整数的判断。当临时list写到与input数组长度一致的时候,是递归的base case,这个时候我们要把这个临时的temp写入res里面去,然后在返回上一层的temp.remove()逐步把temp清空。然后回到本段话的最开始。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值