【代码训练营】day 26 | 39. 组合总和 & 40.组合总和II & 131.分割回文串

所用代码 java

组合总和 LeetCode 39

题目链接:组合总和 LeetCode 39 - 中等

思路

难点在于如何去重!以及树的深度不确定

示意图如下:

26.1.jpg

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        backtarcking(candidates, target, 0);
        return res;
    }

    public void backtarcking(int[] candidates, int target, int startIndex){
        // 大于就返回 剪枝
        if (sum > target) return;
        if (sum == target){
            res.add(new ArrayList<>(path));
            return;
        }
		// i = startIndex 表示从哪一个元素开始
        for (int i = startIndex; i < candidates.length; i++) {
            sum += candidates[i];
            path.add(candidates[i]);
            backtarcking(candidates, target, i);
            // 回溯
            sum -= candidates[i];
            path.remove(path.size()-1);
        }
    }
}

总结

注意startIndex与index的区别,一般我们用startIndex来表示指向数组或字符串的某个元素,用index表示遍历到了第几个数组。

剪枝优化: 通常在for循环做文件,剪枝剪的就是树的分支。本题可先对candidates进行排序,若遇到下一层的和大于target的情况,就没必要继续往下搜索了。

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        // 先排序,前面的加起来大于target之和,后面的就不用考虑了
        Arrays.sort(candidates);
        
        backtarcking(candidates, target, 0);
        return res;
    }

    public void backtarcking(int[] candidates, int target, int startIndex){
        if (sum == target){
            res.add(new ArrayList<>(path));
            return;
        }
		
        for (int i = startIndex; i < candidates.length; i++) {
            // 直接在for训练里面进行判断,可少进行一次回溯
            if (sum + candidates[i] > target) return;
            
            sum += candidates[i];
            path.add(candidates[i]);
            backtarcking(candidates, target, i);
            sum -= candidates[i];
            path.remove(path.size()-1);
        }
    }
}

组合总和II LeetCode 40

题目链接:组合总和II LeetCode 10 - 中等

思路

关键是如何在搜索的过程中进行去重:即树层去重、树枝去重

示意图如下:

26.2.jpg
去重的关键在于定义了一个used数组来记录是否被访问过!

class Solution {
    List<Integer> path = new ArrayList<>();
    List<List<Integer>> res = new ArrayList<>();
    int sum = 0;
    // 定义一个used数组来存数层的元素是否被访问过 -- 横向(宽度)
    int[] used;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        // 初始化为和candidates一样长的数组,值全0
        // 1 表示该元素被访问过; 0 表示未被访问过
        used = new int[candidates.length];
        Arrays.sort(candidates);
        backtracking(candidates, target, 0);
        return res;
    }

    public void backtracking(int[] candidates, int target, int startIndex){
        // 结束递归条件
        if (sum == target) {
            res.add(new ArrayList<>(path));
            return;
        }

        // 单层递归逻辑 -- 同样先剪枝,直接写在for循环里面
        for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
            // 树层方向去重
            // 若第二个元素等于第一个,且第一个未被访问过就跳过
            if (i != 0 && candidates[i-1] == candidates[i] && used[i-1] == 0) {
                continue;
            }
            sum += candidates[i];
            path.add(candidates[i]);
            // 每次遍历深度方向上,把该位置元素置为1
            used[i] = 1;
            backtracking(candidates, target, i+1);
            // 回溯
            sum -= candidates[i];
            path.remove(path.size()-1);
            used[i] = 0; // 同意回溯是要把标记为置0
        }
    }
}

总结

本题主要的麻烦是去重问题,而去重又分为数层去重(横向)和树枝去重(纵向),根据此我们定义了一个used[]数组来存放访问信息,访问过的元素就标记为1,当我们访问的元素等于前一个元素时,即candidates[i-1] == candidates[i]的情况

  • 若used[i-1] == 0,说明同一树层的元素访问过,可考虑数层去重
  • 若used[i-1] == 1,说明同一树枝的元素访问过,可考虑树枝去重

具体为什么可看下图:

20221021163812.png

剪枝操作:本次剪枝操作是直接放在for循环条件里面的,和上一次放在循环里面效果是一样的

for (int i = startIndex; i < candidates.length && sum + candidates[i] <= target; i++) {
    ...
}

分割回文串 LeetCode 131

题目链接:分割回文串 LeetCode 131 - 中等

思路

本题主要是对字符串的切割需找准方向,然后通过判断是否为回文数加入list。

主要思路如图:

131.分割回文串.jpg

class Solution {
    List<String> path = new ArrayList<>();
    List<List<String>> res = new ArrayList<>();
    public List<List<String>> partition(String s) {
        backtracking(s, 0);
        return res;
    }

    // startIndex 表示切割线,如a|ab
    public void backtracking(String s, int startIndex){
        if (startIndex >= s.length()){
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < s.length(); i++) {
            if (isPalindrome(s, startIndex, i)){
//                System.out.println("startIndex = " +startIndex);
                // substring 左闭右开
                String str = s.substring(startIndex, i + 1);
//                System.out.println("str = " + str);
                path.add(str);
            }else continue;

            backtracking(s, i+1);
            path.remove(path.size()-1);
        }
    }

    // 左闭右闭 -- 因为i取到的最后一个数是s.length()-1
    public boolean isPalindrome(String s, int i, int j){
        // 不用取等比较中间那个数
        while (i < j){
            if (s.charAt(i) != s.charAt(j)){
                return false;
            }
            i++;
            j--;
        }
        // 只有一个字符返回true
        return true;
    }
}

总结

本题主要考虑三个点:

  1. 切割的时候,切割的起始位置(startIndex)和终止位置(i)怎么判断
  2. 回溯的时候,应从字符串第二个字符开始
  3. 判断回文数,应设计成左闭右闭
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值