代码随想录刷题day23丨39. 组合总和,40.组合总和II, 131.分割回文串

代码随想录刷题day23丨39. 组合总和,40.组合总和II, 131.分割回文串

1.题目

1.1组合总和

  • 题目链接:39. 组合总和 - 力扣(LeetCode)

    在这里插入图片描述

  • 视频讲解:带你学透回溯算法-组合总和(对应「leetcode」力扣题目:39.组合总和)| 回溯法精讲!_哔哩哔哩_bilibili

  • 文档讲解:https://programmercarl.com/0039.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8C.html

  • 解题思路:回溯

    • 本题搜索的过程抽象成树形结构如下:

      在这里插入图片描述

    • 注意图中叶子节点的返回条件,因为本题没有组合数量要求,仅仅是总和的限制,所以递归没有层数的限制,只要选取的元素总和超过target,就返回!

    • 回溯三部曲

      • 递归函数参数

        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        void backtracking(int[] candidates,int target,int sum,int startIndex)
        
      • 递归终止条件

        if(sum > target){
            return;
        }
        if(sum == target){
            result.add(new ArrayList<>(path));
            return;
        }
        
      • 单层搜索的逻辑

        for(int i = startIndex;i < candidates.length;i++){
            path.add(candidates[i]);
            sum += candidates[i];
            backtracking(candidates,target,sum,i);
            sum -= candidates[i];
            path.remove(path.size() -1);
        }
        
  • 代码:

    class Solution {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            backtracking(candidates,target,0,0);
            return result;
        }
    
        void backtracking(int[] candidates,int target,int sum,int startIndex){
            if(sum > target){
                return;
            }
            if(sum == target){
                result.add(new ArrayList<>(path));
                return;
            }
            for(int i = startIndex;i < candidates.length;i++){
                path.add(candidates[i]);
                sum += candidates[i];
                backtracking(candidates,target,sum,i);
                sum -= candidates[i];
                path.remove(path.size() -1);
            }
        }
    }
    
    • 剪枝优化

      class Solution {
          List<Integer> path = new ArrayList<>();
          List<List<Integer>> result = new ArrayList<>();
          public List<List<Integer>> combinationSum(int[] candidates, int target) {
              Arrays.sort(candidates); // 先进行排序
              backtracking(candidates,target,0,0);
              return result;
          }
      
          void backtracking(int[] candidates,int target,int sum,int startIndex){
              if(sum > target){
                  return;
              }
              if(sum == target){
                  result.add(new ArrayList<>(path));
                  return;
              }
              for(int i = startIndex;i < candidates.length;i++){
                  // 如果 sum + candidates[i] > target 就终止遍历
                  if (sum + candidates[i] > target) break;
                  path.add(candidates[i]);
                  sum += candidates[i];
                  backtracking(candidates,target,sum,i);
                  sum -= candidates[i];
                  path.remove(path.size() -1);
              }
          }
      }
      
  • 总结:

    • 在求和问题中,排序之后加剪枝是常见的套路!

1.2组合总和II

  • 题目链接:40. 组合总和 II - 力扣(LeetCode)

    在这里插入图片描述

  • 视频讲解:回溯算法中的去重,树层去重树枝去重,你弄清楚了没?| LeetCode:40.组合总和II_哔哩哔哩_bilibili

  • 文档讲解:https://programmercarl.com/0040.%E7%BB%84%E5%90%88%E6%80%BB%E5%92%8CII.html

  • 解题思路:回溯

    • 集合(数组candidates)有重复元素,但还不能有重复的组合

    • 我们要去重的是同一树层上的“使用过”,同一树枝上的都是一个组合里的元素,不用去重

    • 强调一下,树层去重的话,需要对数组排序!

    • 选择过程树形结构如图所示:

      在这里插入图片描述

  • 代码:

    class Solution {
        List<Integer> path = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
    
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);  // 先排序
            backtracking(candidates, target, 0, 0);
            return result;
        }
    
        void backtracking(int[] candidates, int target, int sum, int startIndex) {
            if (sum > target) {
                return;
            }
            if (sum == target) {
                result.add(new ArrayList<>(path));
                return;
            }
            for (int i = startIndex; i < candidates.length; i++) {
                // 跳过相同的元素,避免产生重复组合
                if (i > startIndex && candidates[i] == candidates[i - 1]) {
                    continue;
                }
    
                // 如果当前元素加上sum大于目标值,则不继续遍历
                if (sum + candidates[i] > target) {
                    break;
                }
                path.add(candidates[i]);
                sum += candidates[i];
                backtracking(candidates, target, sum, i+1);
                sum -= candidates[i];
                path.remove(path.size() - 1);
            }
        }
    }
    
  • 总结:

    • 直接用startIndex来去重

1.3分割回文串

  • 题目链接:131. 分割回文串 - 力扣(LeetCode)

    在这里插入图片描述

  • 视频讲解:带你学透回溯算法-分割回文串(对应力扣题目:131.分割回文串)| 回溯法精讲!_哔哩哔哩_bilibili

  • 文档讲解:https://programmercarl.com/0131.%E5%88%86%E5%89%B2%E5%9B%9E%E6%96%87%E4%B8%B2.html

  • 解题思路:回溯

    • 本题涉及到两个关键问题:

      • 切割问题,有不同的切割方式
      • 判断回文
    • 回文串是向前和向后读都相同的字符串。

    • 我们来分析一下切割,其实切割问题类似组合问题

      • 例如对于字符串abcdef:
        • 组合问题:选取一个a之后,在bcdef中再去选取第二个,选取b之后在cdef中再选取第三个…。
        • 切割问题:切割一个a之后,在bcdef中再去切割第二段,切割b之后在cdef中再切割第三段…。
    • 所以切割问题,也可以抽象为一棵树形结构,如图:

      在这里插入图片描述

    • 递归用来纵向遍历,for循环用来横向遍历,切割线(就是图中的红线)切割到字符串的结尾位置,说明找到了一个切割方法。

    • 此时可以发现,切割问题的回溯搜索的过程和组合问题的回溯搜索的过程是差不多的。

    • 回溯三部曲

      • 递归函数参数

        List<String> path = new ArrayList<>();
        List<List<String>> result = new ArrayList<>();
        void backtracking(String s,int startIndex)
        
      • 递归函数终止条件

        if(startIndex == s.length()){ // 递归终止条件:当索引遍历到字符串末尾时
            result.add(new ArrayList<>(path));// 将当前的分割路径 `path` 加入到 `result` 中
            return;
        }
        
      • 单层搜索的逻辑

        StringBuilder sb = new StringBuilder();
        for(int i = startIndex;i < s.length();i++){
            sb.append(s.charAt(i));// 将从 startIndex 开始的字符逐个加入 StringBuilder
            if(check(sb)){ // 如果当前的子串是回文串
                path.add(sb.toString());// 将该回文子串加入当前路径
                backtracking(s,i + 1);// 递归从下一个字符开始
                path.remove(path.size() -1);// 回溯,移除刚刚加入的回文子串
            }
        }
        
  • 代码:

    class Solution {
        List<String> path = new ArrayList<>();
        List<List<String>> result = new ArrayList<>();
    
        public List<List<String>> partition(String s) {
            backtracking(s,0);// 开始进行回溯,从索引0开始
            return result;// 返回最终的所有分割结果
        }
    
        void backtracking(String s,int startIndex){
            if(startIndex == s.length()){ // 递归终止条件:当索引遍历到字符串末尾时
                result.add(new ArrayList<>(path));// 将当前的分割路径 `path` 加入到 `result` 中
                return;
            }
            StringBuilder sb = new StringBuilder();
            for(int i = startIndex;i < s.length();i++){
                sb.append(s.charAt(i));// 将从 startIndex 开始的字符逐个加入 StringBuilder
                if(check(sb)){ // 如果当前的子串是回文串
                    path.add(sb.toString());// 将该回文子串加入当前路径
                    backtracking(s,i + 1);// 递归从下一个字符开始
                    path.remove(path.size() -1);// 回溯,移除刚刚加入的回文子串
                }
            }
        }
    
        //检查是否是回文
        private boolean check(StringBuilder sb){
            for(int i = 0;i < sb.length()/2;i++){
                if(sb.charAt(i) != sb.charAt(sb.length() - 1 - i)){ // 检查首尾字符是否相等
                    return false;
                }
            }
            return true;
        }
    }
    
  • 总结:

    • 切割线切到了字符串最后面,说明找到了一种切割方法,此时就是本层递归的终止条件。
    • 那么在代码里什么是切割线呢?
      • 在处理组合问题的时候,递归参数需要传入startIndex,表示下一轮递归遍历的起始位置,这个startIndex就是切割线。
    • 在递归循环中如何截取子串呢?
      • 在for循环中,我们 定义了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。
      • 首先判断这个子串是不是回文,如果是回文,就加入在path中,path用来记录切割过的回文子串。
      • 注意切割过的位置,不能重复切割,所以,backtracking(s, i + 1); 传入下一层的起始位置为i + 1
    • 如何判断一个字符串是否是回文?
      • 可以使用双指针法,一个指针从前向后,一个指针从后向前,如果前后指针所指向的元素是相等的,就是回文字符串了。
    • 本题有如下几个难点:
      • 切割问题可以抽象为组合问题
      • 如何模拟那些切割线
      • 切割问题中递归如何终止
      • 在递归循环中如何截取子串
      • 如何判断回文
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值