递归与回溯区别(附leetcode相关题)

一.递归是一种算法结构:

为了描述问题的某一状态,必须用到该状态的上一状态,而描述上一状态,又必须用到上一状态的上一状态……这种用自已来定义自己的方法,称为递归定义。形式如 f(n) = n*f(n-1), if n=0,f(n)=1.

二.回溯是一种算法思想,可以用递归实现。

从问题的某一种可能出发, 搜索从这种情况出发所能达到的所有可能, 当这一条路走到” 尽头 “的时候, 再倒回出发点, 从另一个可能出发, 继续搜索. 这种不断” 回溯 “寻找解的方法, 称作” 回溯法 “。

三.leetcode递归回溯相关题

1.leetcode 17 题 (电话号码的字母组合)
在这里插入图片描述

class Solution {
    private List<String> combinations = new ArrayList<>();
    private Map<Character, String> phoneMap = new HashMap<Character, String>() {{
        put('2', "abc");
        put('3', "def");
        put('4', "ghi");
        put('5', "jkl");
        put('6', "mno");
        put('7', "pqrs");
        put('8', "tuv");
        put('9', "wxyz");
    }};
    public List<String> letterCombinations(String digits) {
        if(digits.length()==0){
            return combinations;
        } else{
            backtrack(digits,0,new StringBuffer());
            return combinations;
        }
    }
    private void backtrack(String digist, int index, StringBuffer combination){
        if(index == digist.length()){
            combinations.add(combination.toString());
        } else{
            char digit = digist.charAt(index);
            String letters = phoneMap.get(digit);
            for(int i =0 ; i<letters.length();i++){
                combination.append(letters.charAt(i));
                backtrack(digist,index+1,combination);
                combination.deleteCharAt(index);
            }
        }
    }
}

2. leetcode 22 题 (括号生成)

在这里插入图片描述

class Solution {
    List<String> res = new ArrayList<>();

    public List<String> generateParenthesis(int n) {
        if (n < 0) {
            return res;
        }
        getParenthesis("(", n - 1, n);
        return res;
    }

    private void getParenthesis(String str, int left, int right) {
        if (left == 0 && right == 0) {
            res.add(str);
            return;
        }
        if (left == right) {
            getParenthesis(str + "(", left - 1, right);
        } else {
            if (left < right) {
                if (left > 0) {
                    getParenthesis(str + "(", left - 1, right);
                }
                getParenthesis(str + ")", left, right - 1);
            }
        }
    }
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值