1. 组合总和问题概述
LeetCode上的组合总和问题(Combination Sum)是算法练习中的经典题目,要求找出所有能使数字和等于目标值的候选数字组合。这类问题在技术面试中出现频率极高,尤其考察候选人对回溯算法的理解和优化能力。
我最初接触这个问题时,曾陷入暴力枚举的误区,后来通过系统学习和反复实践,才真正掌握了回溯与剪枝的精髓。这道题的Java实现看似简单,但要做到高效和优雅,需要深入理解几个关键点:
- 候选数字可以无限制重复选取
- 解集不能包含重复组合
- 需要找到所有可能的解而非最优解
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 回溯算法基础实现
2.1 基本回溯框架
回溯算法的核心是尝试所有可能的路径,并在不满足条件时回退。对于组合总和问题,最基本的Java实现如下:
java复制public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), candidates, target, 0);
return result;
}
private void backtrack(List<List<Integer>> result, List<Integer> tempList,
int[] candidates, int remain, int start) {
if (remain < 0) return;
if (remain == 0) {
result.add(new ArrayList<>(tempList));
return;
}
for (int i = start; i < candidates.length; i++) {
tempList.add(candidates[i]);
backtrack(result, tempList, candidates, remain - candidates[i], i);
