39.组合总和

39.组合总和

题目

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

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

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

示例 1:

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

示例 2:

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

示例 3:

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

提示:

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

解题思路

最初,为了避免使用递归来解决这个组合问题,我决定采用一种迭代的、类似广度优先搜索(BFS)的思路。我想,我需要一个队列来管理所有待探索的“部分组合”。为了清晰地追踪每一个部分组合的状态,我定义了一个 State 类,它包含当前的和 currentSum、已选路径 currentPath 以及一个关键的 startIndex,这个 startIndex 是为了确保我能正确地重复使用数字,并且避免生成像 [2,3] 和 [3,2] 这样因顺序不同而产生的重复组合。在开始探索前,我对候选数字 candidates 进行了排序,主要是为了后续如果某个数字加入后使得总和超标,我就可以利用排序的特性提前终止对更大数字的尝试(剪枝)。我的探索从一个初始状态(总和为0,路径为空,startIndex为0),即 queue.offer(new State(0, new ArrayList<>(), 0)) 放入队列开始。然后,我进入一个主循环,只要队列不空(while(!queue.isEmpty())),就取出队首的状态。对于取出的每个状态,我尝试从其 startIndex 开始,遍历 candidates 数组中的数字来扩展当前路径——这里特别注意,每次扩展生成新路径时,我都会创建一个当前路径的副本(如 new ArrayList<>(ans.currentPath)),以防不同分支互相干扰。在加入一个新数字后,如果新总和恰好等于目标值(newSum == target),我就把这条新路径存入结果集;如果小于目标值(newSum < target**),我就把这个新形成的(包含新总和、新路径以及当前数字索引 **i** 作为新的 **startIndex**,以便允许这个数字被再次使用)的状态放入队列(即 **queue.offer(new State(newSum, newPath, i))**)等待进一步处理;如果大于目标值(**newSum > target),并且因为数组已排序,我就直接中断对当前状态后续数字的尝试(break)。就这样,通过队列的先进先出和 startIndex 的巧妙控制(它既保证了从当前及后续可选,又因其在循环中递增而避免了回头选导致重复),我系统地构建并筛选出了所有符合条件的组合到 res 中。


详细代码

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
// 定义一个辅助类来存储队列中的状态
class State {
int currentSum;
List<Integer> currentPath;
int startIndex;

State(int sum, List<Integer> path, int index) {
this.currentSum = sum;
this.currentPath = path;
this.startIndex = index;
}
}

class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> res=new ArrayList<>();
Queue<State> queue=new LinkedList<>();
Arrays.sort(candidates);
queue.offer(new State(0,new ArrayList<>(),0));

while(!queue.isEmpty()){
State ans=queue.poll();

for (int i=ans.startIndex;i<candidates.length; i++){
int candidateValue=candidates[i];
int newSum=ans.currentSum+candidateValue;

List<Integer> newPath=new ArrayList<>(ans.currentPath);
newPath.add(candidateValue);

if(newSum==target){
res.add(newPath);
}else if(newSum<target)
queue.offer(new State(newSum,newPath,i));
else break;
}
}
return res;
}
}