代码随想录算法训练营第30天 || 39.组合总和 || 40.组合总和II || 131.分割回文串

代码随想录算法训练营第30天 || 39.组合总和 || 40.组合总和II || 131.分割回文串

39. 组合总和

题目简介:

  • 给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

    candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。

    对于给定的输入,保证和为 target 的不同组合数少于 150 个。

    示例 1:

    输入:candidates = [2,3,6,7], target = 7
    输出:[[2,2,3],[7]]
    解释:
    2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
    7 也是一个候选, 7 = 7 。
    仅有这两种组合。
    

    示例 2:

    输入: candidates = [2,3,5], target = 8
    输出: [[2,2,2,2],[2,3,3],[3,5]]
    

    示例 3:

    输入: candidates = [2], target = 1
    输出: []
    

个人思路:

组合问题(不放回),考虑使用回溯法

先对数组排序一下,方便之后的操作

回溯三部曲

  • 确定回溯参数和返回值

    • 参数:int数组,target,sum,deep(用于记录这是第几层递归,第一层for循环递归每一次传入的数组
    • 返回值:void
  • 确定递归结束条件:遇到sum == target时保存不重复结果,当sum > target时,结束本层递归

  • 确定单层递归逻辑:区分第一层和其它层

    for (int i = startIndex; i < candidates.length; i++) {
        if (sum + candidates[i] > target)//剪枝操作
            break;
        list.add(candidates[i]);
        if (deep == 1)
            backstracking(candidates, target, sum + candidates[i], deep + 1);
        else backstracking(candidates, target, sum + candidates[i], deep + 1);
        list.remove(list.size() - 1);
    }
    

代码:

class Solution {
    public List<List<Integer>> result = new ArrayList<>();
    public List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backstracking(candidates, target, 0, 1);
        return result;
    }

    public void backstracking(int[] candidates, int target, int sum, int deep) {
        if (sum == target) {
            ArrayList<Integer> temp = new ArrayList<>(list);
            Collections.sort(temp);
            if (!result.contains(temp))
                result.add(temp);
            return;
        }
        for (int i = 0; i < candidates.length; i++) {
            if (sum + candidates[i] > target)//剪枝操作
                break;
            list.add(candidates[i]);
            if (deep == 1)
                backstracking(Arrays.copyOfRange(candidates, i, candidates.length), target, sum + candidates[i], deep + 1);
            else backstracking(candidates, target, sum + candidates[i], deep + 1);
            list.remove(list.size() - 1);
        }

    }
}

题解优化:

第一处优化:没有必要区分第一层或其他层不同处理逻辑,将其修改为startIndex(startIndex为for循环中的i)版本,还可以省去去重操作

public void backstracking(int[] candidates, int target, int sum, int startIndex) {

第二处优化:if (sum + candidates[i] > target)//剪枝操作,先做排序,才能这样剪枝

class Solution {
    public List<List<Integer>> result = new ArrayList<>();
    public List<Integer> list = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        backstracking(candidates, target, 0, 0);
        return result;
    }

    public void backstracking(int[] candidates, int target, int sum, int startIndex) {
        if (sum == target) {
            result.add(new ArrayList<>(list));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (sum + candidates[i] > target)//剪枝操作
                break;
            list.add(candidates[i]);
            backstracking(candidates, target, sum + candidates[i], i);
            list.remove(list.size() - 1);
        }
    }
}

40.组合总和II

题目简介:

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次

**注意:**解集不能包含重复的组合。

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

个人思路:

基本思路和上一题类似,题意上有点变动,给的数组可能有重复元素,且每个数字只能使用一次

两个差别:

  • 需要在for循环中做一个剪枝(数组已排序):同一个数字得到的结果会相同,直接跳过
if (i > startIndex && candidates[i] == candidates[i - 1])
    continue;

代码:

    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 sum, int startIndex) {
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            //只要i>startIndex,表明此元素至少是该层第二个元素,前面那个元素必然在该层使用过,避免出现前面那个元素是上一层用过的
            if (i > startIndex && candidates[i] == candidates[i - 1])//剪枝1
                continue;
            if (sum + candidates[i] > target)//剪枝2
                break;
            path.add(candidates[i]);
            backtracking(candidates, target, sum + candidates[i], i + 1);
            path.remove(path.size() - 1);
        }

    }
}

题解补充:

本题涉及到的是树层去重,此前做的都是树枝去重

  • 树层去重:for循环中,continue跳过该层
  • 树枝去重:for循环中,break跳出循环

题解中提供两种树枝去重思路:

  • 和上述代码一样,直接使用startIndex去重
  • 使用标记数组法,多使用一个传参,进行标记使用过的元素
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {
            // used[i - 1] == true,说明同一树枝candidates[i - 1]使用过
            // used[i - 1] == false,说明同一树层candidates[i - 1]使用过
            // 要对同一树层使用过的元素进行跳过
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            sum += candidates[i];
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i + 1, used); // 和39.组合总和的区别1,这里是i+1,每个数字在每个组合中只能使用一次
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }

131.分割回文串

题目简介:

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"
输出:[["a"]]

个人思路:

主要考察树层剪枝

递归三部曲:

  • 确定参数和返回值:
    • 参数:字符数组、循环开始下标
    • 返回值:void
  • 确定递归结束条件:循环开始下标 == 数组长度时,保存结果并退出本层递归
  • 单层递归逻辑:逐渐扩大切割的子串范围,子串不是回文则减掉树层
for (int i = startIndex, j = 1; i < str.length; i++) {
    char[] chars = Arrays.copyOfRange(str, startIndex, startIndex + j++);//从标记处开始,逐渐扩大子串范围
    if (!isPartition(chars))//判断回文,不符则不进入下一层递归
        continue;
    path.add(String.valueOf(chars));
    backtracking(str, i + 1);
    path.remove(path.size() - 1);
}

代码:

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

    public List<List<String>> partition(String s) {
        backtracking(s.toCharArray(), 0);
        return result;
    }

    public void backtracking(char[] str, int startIndex) {
        if (startIndex == str.length) {//标记处越界则保存结果
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex, j = 1; i < str.length; i++) {
            char[] chars = Arrays.copyOfRange(str, startIndex, startIndex + j++);//从标记处开始,逐渐扩大子串范围
            if (!isPartition(chars))//判断回文,不符则不进入下一层递归
                continue;
            path.add(String.valueOf(chars));
            backtracking(str, i + 1);
            path.remove(path.size() - 1);
        }

    }

    public boolean isPartition(char[] str) {//判断回文函数
        int i = 0;
        int j = str.length - 1;
        while (i < j) {
            if (str[i++] != str[j--])
                return false;
        }
        return true;
    }
}

题解中还提供了一种加速判断回文字符串的方法,但涉及到动态规划,先放一放,二刷再看

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值