归档

39. 组合总和

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
  • 输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

题解

让选择下标不递减

题目要求列出和为 target 的组合,同一个候选值可以使用多次,但顺序不同不能算不同组合。path 保存当前选择,remainingTarget 保存还差的和,start 表示本层允许选择的最小下标。

选择下标 i 后,递归仍传入 i,允许继续使用当前值;后续也只能选 i 或更大的下标,所以不会再向前选择,避免生成同一组合的不同顺序。题目保证候选值互异,无须额外跳过同值下标。

例如候选 [2,3,6,7]、目标 7:连续选两次 2 后,剩余目标为 3,可以再选 3 得到 [2,2,3];从 3 开始的路径不能回头选择 2,因此不会重复生成 [3,2,2]。单独选择 7 也是一个解。

排序使超出目标的分支可以整段跳过

先将候选数组升序排列。本层若 candidates[i] > remainingTarget,后面的值只会更大,可以直接 break。候选值都是正数,每次选择都会减少剩余目标,所以搜索可以终止;这个条件也保证递归不会走到负目标。

当 remainingTarget == 0 时复制路径加入答案并返回。否则遍历所有仍可选的值,按“加入、递归、移除末尾”的顺序搜索。如果循环没有可选值,这条路径会自然返回,不需要再设置另一条成功条件。

排序会修改输入数组;若还需原有顺序,应先复制数组再调用。结果必须保存路径副本,否则后续撤销会改变已经记录的组合。

复杂度

设候选数为 n,最小候选为 a,令 $D=\lfloor target/a\rfloor$,路径长度最多为 D。不计结果,路径与递归栈占 $O(D+1)$ 空间,此外还有排序的实现开销。

排序耗时 $O(n\log n)$。搜索耗时取决于实际枚举的递归分支以及答案复制量,最坏呈指数增长;仅写成 $O(n×target)$ 不能描述这里列举所有组合的成本。

完整示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Main {

    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> result = new ArrayList<>();
        if (candidates == null || candidates.length == 0) {
            return result;
        }

        Arrays.sort(candidates);
        backtrack(result, new ArrayList<>(), candidates, target, 0);
        return result;
    }

    private static void backtrack(List<List<Integer>> result, List<Integer> path,
                                  int[] candidates, int remainingTarget, int start) {
        if (remainingTarget == 0) {
            result.add(new ArrayList<>(path));
            return;
        }

        for (int i = start; i < candidates.length; i++) {
            if (candidates[i] > remainingTarget) {
                break;
            }

            path.add(candidates[i]);
            backtrack(result, path, candidates, remainingTarget - candidates[i], i);
            path.remove(path.size() - 1);
        }
    }

    public static void main(String[] args) {
        int[] candidates1 = {2, 3, 6, 7};
        int target1 = 7;
        System.out.println("示例 1 输入: candidates = " + Arrays.toString(candidates1) + ", target = " + target1);
        List<List<Integer>> result1 = combinationSum(candidates1, target1);
        System.out.println("示例 1 输出: " + result1);
        System.out.println("-----------------------------");

        int[] candidates2 = {2, 3, 5};
        int target2 = 8;
        System.out.println("示例 2 输入: candidates = " + Arrays.toString(candidates2) + ", target = " + target2);
        List<List<Integer>> result2 = combinationSum(candidates2, target2);
        System.out.println("示例 2 输出: " + result2);
        System.out.println("-----------------------------");

        int[] candidates3 = {2};
        int target3 = 1;
        System.out.println("示例 3 输入: candidates = " + Arrays.toString(candidates3) + ", target = " + target3);
        List<List<Integer>> result3 = combinationSum(candidates3, target3);
        System.out.println("示例 3 输出: " + result3);
    }
}

运行结果(OpenJDK 21.0.12):

1
2
3
4
5
6
7
8
示例 1 输入: candidates = [2, 3, 6, 7], target = 7
示例 1 输出: [[2, 2, 3], [7]]
-----------------------------
示例 2 输入: candidates = [2, 3, 5], target = 8
示例 2 输出: [[2, 2, 2, 2], [2, 3, 3], [3, 5]]
-----------------------------
示例 3 输入: candidates = [2], target = 1
示例 3 输出: []
本文由作者按照 CC BY 4.0 进行授权