第二十三天|回溯算法| 39. 组合总和,40. 组合总和II,131. 分割回文串

目录

39. 组合总和

未剪枝

剪枝优化

40. 组合总和II

131. 分割回文串

回溯

回溯+动态规划优化回文串判断


今天的题目自己都没啥思路,二刷的时候再理解一下。尤其是131.

39. 组合总和

本题和77.组合 216.组合总和III的区别是:本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。

未剪枝

对于sum已经大于target的情况,其实是依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。

其实如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。

class Solution {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backTracking(candidates,target,0);
        return result;
    }
    public void backTracking(int[] candidates, int target, int index) {
        if (sum == target){
            result.add(new ArrayList<>(path));
            return;
        }
        if (sum > target) return;
        for (int i = index; i < candidates.length; i++) {
            path.add(candidates[i]);
            sum += candidates[i];
            backTracking(candidates,target,i);
            sum -= candidates[i];
            path.removeLast();
        }
    }
}

剪枝优化

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

对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。

for循环剪枝代码如下:

for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)
  • 时间复杂度: O(n * 2^n),注意这只是复杂度的上界,因为剪枝的存在,真实的时间复杂度远小于此
  • 空间复杂度: O(target)
    // 剪枝优化
    class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res = new ArrayList<>();
            Arrays.sort(candidates); // 先进行排序
            backTracking(res, new ArrayList<>(), candidates, target, 0, 0);
            return res;
        }

        public void backTracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) {
            // 找到了数字和为 target 的组合
            if (sum == target) {
                res.add(new ArrayList<>(path));
                return;
            }
            for (int i = idx; i < candidates.length; i++) {
                // 如果 sum + candidates[i] > target 就终止遍历
                if (sum + candidates[i] > target) break;
                path.add(candidates[i]);
                backTracking(res, path, candidates, target, sum + candidates[i], i);
                path.remove(path.size() - 1);// 回溯,移除路径 path 最后一个元素
            }
        }
    }

40. 组合总和II

本题的难点在于:集合(数组candidates)有重复元素,但还不能有重复的组合

元素在同一个组合内是可以重复的,怎么重复都没事,但两个组合不能相同。

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

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

此题注意理解去重即可。

    class Solution {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();

        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            //为了将重复的数字都放到一起,所以先进行排序
            Arrays.sort(candidates);
            backtracking(candidates, target, 0, 0);
            return result;
        }

        public void backtracking(int[] candidates, int target, int startIndex, int sum) {
            if (sum == target) {
                result.add(new ArrayList<>(path));
                return;
            }
            for (int i = startIndex; i < candidates.length; i++) {
                //正确剔除重复解的办法
                //跳过同一树层使用过的元素
                if (sum + candidates[i] > target) break; // 剪枝
                if (i != startIndex && candidates[i] == candidates[i-1]) continue; // 去重
                path.add(candidates[i]);
                // i+1 代表当前组内元素只选取一次
                backtracking(candidates, target, i + 1, sum + candidates[i]);
                path.removeLast();
            }
        }
    }

131. 分割回文串

有点难,自己写不出来,之后再来过一遍

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

  1. 切割问题(类似组合问题),有不同的切割方式
  2. 判断回文

  • 在递归循环中截取子串

for (int i = startIndex; i < s.size(); i++)循环中,我们 定义了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。

首先判断这个子串是不是回文,如果是回文,就加入在vector<string> path中,path用来记录切割过的回文子串。

注意切割过的位置,不能重复切割,所以,backtracking(s, i + 1); 传入下一层的起始位置为i + 1

  • 判断回文子串

双指针法,一个指针从前向后,一个指针从后向前,如果前后指针所指向的元素是相等的,就是回文字符串了。

列出本题的几个难点:

  • 切割问题可以抽象为组合问题
  • 如何模拟那些切割线
  • 切割问题中递归如何终止
  • 在递归循环中如何截取子串
  • 如何判断回文

回溯

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

        public List<List<String>> partition(String s) {
            backtracking(s, 0, new StringBuilder());
            return res;
        }

        private void backtracking(String s, int start, StringBuilder sb) {
            //因为是起始位置一个一个加的,所以结束时start一定等于s.length,因为进入backtracking时一定末尾也是回文,所以cur是满足条件的
            if (start == s.length()) { // 已经处理完字符串的所有字符
                //注意创建一个新的copy
                res.add(new ArrayList<>(cur)); // 将 cur 的一个副本加入 res。
                return;
            }
            //像前两题一样从前往后搜索,如果发现回文,进入backtracking,起始位置后移一位,循环结束照例移除cur的末位
            for (int i = start; i < s.length(); i++) {
                sb.append(s.charAt(i));
                if (check(sb)) {
                    cur.add(sb.toString());
                    backtracking(s, i + 1, new StringBuilder()); // 不能重复切割,所以,backtracking(s, i + 1); 传入下一层的起始位置为i + 1。
                    cur.remove(cur.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;
        }
    }

回溯+动态规划优化回文串判断

详细解释见注释

这个代码通过动态规划和回溯结合,先用动态规划确定所有可能的回文子串,再通过回溯法找到所有有效的划分。与前一个版本相比,这个版本利用 dp 数组提前判断回文子串,从而避免重复计算,使得回溯过程更加高效。

    // 回溯+动态规划优化回文串判断
    class Solution {
        List<List<String>> result;
        LinkedList<String> path;
        boolean[][] dp; // dp[i][j] 表示字符串从第 i 个字符到第 j 个字符是否是回文子串。

        public List<List<String>> partition(String s) {
            result = new ArrayList<>();
            char[] str = s.toCharArray();
            path = new LinkedList<>();
            dp = new boolean[str.length + 1][str.length + 1];
            isPalindrome(str);
            backtracking(s, 0);
            return result;
        }

        //startIndex 是当前处理的起始位置。
        public void backtracking(String str, int startIndex) {
            if (startIndex >= str.length()) {
                //如果起始位置大于s的大小,说明找到了一组分割方案
                result.add(new ArrayList<>(path));
            } else {
                // 从 startIndex 开始遍历,逐步扩大到 i(表示当前子串的结束位置)
                for (int i = startIndex; i < str.length(); i++) {
                    if (dp[startIndex][i]) {
                        //是回文子串,进入下一步递归
                        //先将当前子串保存入path
                        path.addLast(str.substring(startIndex, i + 1));
                        //起始位置后移,保证不重复
                        backtracking(str, i + 1); // 继续搜索后续部分。
                        path.pollLast();// 回溯,移除当前子串,以尝试其他可能的划分
                    } else {
                        //不是回文子串,跳过
                        continue;
                    }
                }
            }
        }

        //通过动态规划判断是否是回文串,参考动态规划篇 52 回文子串
        public void isPalindrome(char[] str) {
            // dp[i][i] 初始化为 true,因为任何一个字符自身都是回文
            for (int i = 0; i <= str.length; i++) {
                dp[i][i] = true;
            }
            for (int i = 1; i < str.length; i++) {
                for (int j = i; j >= 0; j--) {
                    if (str[j] == str[i]) {
                        if (i - j <= 1) { // 两个字符相邻或相同
                            dp[j][i] = true; // 如 "aa" 是回文
                            //否则,如果 str[j] == str[i] 且内部的子串 str[j+1] 到 str[i-1] 也是回文(即 dp[j+1][i-1] == true),
                            // 那么 str[j] 到 str[i] 也是回文,所以设置 dp[j][i] = true。
                        } else if (dp[j + 1][i - 1]) {
                            dp[j][i] = true;
                        }
                    }
                }
            }
        }
    }

第二十三天的总算是结束了,直冲Day24!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值