从零刷算法-组合总和

96 阅读1分钟

「这是我参与2022首次更文挑战的第18天,活动详情查看:2022首次更文挑战」。

题目描述

给你一个 无重复元素 的整数数组 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
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都 互不相同
  • 1 <= target <= 500

题目链接:组合总和

思路介绍

  • 首先对特殊情况处理,创建程序出口
  • 这里要事先对数组进行排序,这样可以在后面的遍历中提前结束遍历
  • 然后进入回溯方法体,首先创建方法体出口,也就是当与目标值差为 0 的时候代表找到了一组数据,放入结果集
  • 为了不重复遍历元素,在 for 循环内就让 i 从 index 开始
  • 接下来关键一步在循环一开始就先判断目标值是否小于当前遍历元素,如果小于,则说明后面元素都比 target 大,直接 break 跳出循环,否则才能继续遍历寻找元素直到与 target 值相等。
  • 遍历完所有元素之后,满足题意的数组对已经放入了结果集,直接返回 ans 即可。

代码

​
class Solution {
    List<List<Integer>> ans = new ArrayList<>();
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates == null || candidates.length == 0 || target < 0) {
            return ans;
        }
        // 排序为了后面可以提前结束遍历
        Arrays.sort(candidates);
        List<Integer> tmp = new ArrayList<>();
        // 回溯
        back(candidates, target, 0, tmp);
        return ans;
    }
    
    private void back(int[] candidates, int target, int index, List<Integer> tmp) {
        // 当目标值为 0,也就是刚好找到某些数的和为 target
        if (target == 0) {
            ans.add(new ArrayList<>(tmp));
            return;
        }
        // 这里为了不重复遍历,让 i 从 index 开始
        for (int i = index; i < candidates.length; i++) {
            
            // 在数组有序的前提下剪枝极大提高效率
            if (target - candidates[i] < 0) {
                break;
            }
            tmp.add(candidates[i]);
            back(candidates, target - candidates[i], i, tmp);
            tmp.remove(tmp.size() - 1);
        }
    }
}

运行结果

执行结果:通过

执行用时:2 ms

内存消耗:41.8 MB