参与本项目 ,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们受益! 组合总和 力扣题目链接 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 candidates 中的数字可以无限制重复被选取。 说明: 所有数字(包括 target)都是正整数。 解集不能包含重复的组合。
参与本项目,贡献其他语言版本的代码,拥抱开源,让更多学习算法的小伙伴们受益!
给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
candidates 中的数字可以无限制重复被选取。
说明:
示例 1:
示例 2:
《代码随想录》算法视频公开课:,相信结合视频再看本篇题解,更有助于大家对本题的理解。
题目中的无限制重复被选取,吓得我赶紧想想 出现0 可咋办,然后看到下面提示:1 <= candidates[i] <= 200,我就放心了。
本题和77.组合,216.组合总和III的区别是:本题没有数量要求,可以无限重复,但是有总和的限制,所以间接的也是有个数的限制。
本题搜索的过程抽象成树形结构如下:

注意图中叶子节点的返回条件,因为本题没有组合数量要求,仅仅是总和的限制,所以递归没有层数的限制,只要选取的元素总和超过target,就返回!
而在77.组合和216.组合总和III 中都可以知道要递归K层,因为要取k个元素的组合。
这里依然是定义两个全局变量,二维数组result存放结果集,数组path存放符合条件的结果。(这两个变量可以作为函数参数传入)
首先是题目中给出的参数,集合candidates, 和目标值target。
此外我还定义了int型的sum变量来统计单一结果path里的总和,其实这个sum也可以不用,用target做相应的减法就可以了,最后如何target==0就说明找到符合的结果了,但为了代码逻辑清晰,我依然用了sum。
本题还需要startIndex来控制for循环的起始位置,对于组合问题,什么时候需要startIndex呢?
我举过例子,如果是一个集合来求组合的话,就需要startIndex,例如:77.组合,216.组合总和III。
如果是多个集合取组合,各个集合之间相互不影响,那么就不用startIndex,例如:17.电话号码的字母组合
注意以上我只是说求组合的情况,如果是排列问题,又是另一套分析的套路,后面我在讲解排列的时候会重点介绍。
代码如下:
vector<vector<int>> result; vector<int> path; void backtracking(vector<int>& candidates, int target, int sum, int startIndex)
在如下树形结构中:

从叶子节点可以清晰看到,终止只有两种情况,sum大于target和sum等于target。
sum等于target的时候,需要收集结果,代码如下:
if (sum > target) { return; } if (sum == target) { result.push_back(path); return; }
单层for循环依然是从startIndex开始,搜索candidates集合。
注意本题和77.组合、216.组合总和III的一个区别是:本题元素为可重复选取的。
如何重复选取呢,看代码,注释部分:
for (int i = startIndex; i < candidates.size(); i++) { sum += candidates[i]; path.push_back(candidates[i]); backtracking(candidates, target, sum, i); // 关键点:不用i+1了,表示可以重复读取当前的数 sum -= candidates[i]; // 回溯 path.pop_back(); // 回溯 }
按照关于回溯算法,你该了解这些!中给出的模板,不难写出如下C++完整代码:
// 版本一 class Solution { private: vector<vector<int>> result; vector<int> path; void backtracking(vector<int>& candidates, int target, int sum, int startIndex) { if (sum > target) { return; } if (sum == target) { result.push_back(path); return; } for (int i = startIndex; i < candidates.size(); i++) { sum += candidates[i]; path.push_back(candidates[i]); backtracking(candidates, target, sum, i); // 不用i+1了,表示可以重复读取当前的数 sum -= candidates[i]; path.pop_back(); } } public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { result.clear(); path.clear(); backtracking(candidates, target, 0, 0); return result; } };
在这个树形结构中:

以及上面的版本一的代码大家可以看到,对于sum已经大于target的情况,其实是依然进入了下一层递归,只是下一层递归结束判断的时候,会判断sum > target的话就返回。
其实如果已经知道下一层的sum会大于target,就没有必要进入下一层递归了。
那么可以在for循环的搜索范围上做做文章了。
对总集合排序之后,如果下一层的sum(就是本层的 sum + candidates[i])已经大于target,就可以结束本轮for循环的遍历。
如图:

for循环剪枝代码如下:
for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++)
整体代码如下:(注意注释的部分)
class Solution { private: vector<vector<int>> result; vector<int> path; void backtracking(vector<int>& candidates, int target, int sum, int startIndex) { if (sum == target) { result.push_back(path); return; } // 如果 sum + candidates[i] > target 就终止遍历 for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) { sum += candidates[i]; path.push_back(candidates[i]); backtracking(candidates, target, sum, i); sum -= candidates[i]; path.pop_back(); } } public: vector<vector<int>> combinationSum(vector<int>& candidates, int target) { result.clear(); path.clear(); sort(candidates.begin(), candidates.end()); // 需要排序 backtracking(candidates, target, 0, 0); return result; } };
本题和我们之前讲过的77.组合、216.组合总和III有两点不同:
针对这两个问题,我都做了详细的分析。
并且给出了对于组合问题,什么时候用startIndex,什么时候不用,并用17.电话号码的字母组合做了对比。
最后还给出了本题的剪枝优化,这个优化如果是初学者的话并不容易想到。
在求和问题中,排序之后加剪枝是常见的套路!
可以看出我写的文章都会大量引用之前的文章,就是要不断作对比,分析其差异,然后给出代码解决的方法,这样才能彻底理解题目的本质与难点。
// 剪枝优化 class Solution { public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> res = new ArrayList<>(); Arrays.sort(candidates); // 先进行排序 backtracking(res, new ArrayList<>(), candidates, target, 0, 0); return res; } public void backtracking(List<List<Integer>> res, List<Integer> path, int[] candidates, int target, int sum, int idx) { // 找到了数字和为 target 的组合 if (sum == target) { res.add(new ArrayList<>(path)); return; } for (int i = idx; i < candidates.length; i++) { // 如果 sum + candidates[i] > target 就终止遍历 if (sum + candidates[i] > target) break; path.add(candidates[i]); backtracking(res, path, candidates, target, sum + candidates[i], i); path.remove(path.size() - 1); // 回溯,移除路径 path 最后一个元素 } } }
回溯(版本一)
class Solution: def backtracking(self, candidates, target, total, startIndex, path, result): if total > target: return if total == target: result.append(path[:]) return for i in range(startIndex, len(candidates)): total += candidates[i] path.append(candidates[i]) self.backtracking(candidates, target, total, i, path, result) # 不用i+1了,表示可以重复读取当前的数 total -= candidates[i] path.pop() def combinationSum(self, candidates, target): result = [] self.backtracking(candidates, target, 0, 0, [], result) return result
回溯剪枝(版本一)
class Solution: def backtracking(self, candidates, target, total, startIndex, path, result): if total == target: result.append(path[:]) return for i in range(startIndex, len(candidates)): if total + candidates[i] > target: break total += candidates[i] path.append(candidates[i]) self.backtracking(candidates, target, total, i, path, result) total -= candidates[i] path.pop() def combinationSum(self, candidates, target): result = [] candidates.sort() # 需要排序 self.backtracking(candidates, target, 0, 0, [], result) return result
回溯(版本二)
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: result =[] self.backtracking(candidates, target, 0, [], result) return result def backtracking(self, candidates, target, startIndex, path, result): if target == 0: result.append(path[:]) return if target < 0: return for i in range(startIndex, len(candidates)): path.append(candidates[i]) self.backtracking(candidates, target - candidates[i], i, path, result) path.pop()
回溯剪枝(版本二)
class Solution: def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]: result =[] candidates.sort() self.backtracking(candidates, target, 0, [], result) return result def backtracking(self, candidates, target, startIndex, path, result): if target == 0: result.append(path[:]) return for i in range(startIndex, len(candidates)): if target - candidates[i] < 0: break path.append(candidates[i]) self.backtracking(candidates, target - candidates[i], i, path, result) path.pop()
主要在于递归中传递下一个数字
var ( res [][]int path []int ) func combinationSum(candidates []int, target int) [][]int { res, path = make([][]int, 0), make([]int, 0, len(candidates)) sort.Ints(candidates) // 排序,为剪枝做准备 dfs(candidates, 0, target) return res } func dfs(candidates []int, start int, target int) { if target == 0 { // target 不断减小,如果为0说明达到了目标值 tmp := make([]int, len(path)) copy(tmp, path) res = append(res, tmp) return } for i := start; i < len(candidates); i++ { if candidates[i] > target { // 剪枝,提前返回 break } path = append(path, candidates[i]) dfs(candidates, i, target - candidates[i]) path = path[:len(path) - 1] } }
var combinationSum = function(candidates, target) { const res = [], path = []; candidates.sort((a,b)=>a-b); // 排序 backtracking(0, 0); return res; function backtracking(j, sum) { if (sum === target) { res.push(Array.from(path)); return; } for(let i = j; i < candidates.length; i++ ) { const n = candidates[i]; if(n > target - sum) break; path.push(n); sum += n; backtracking(i, sum); path.pop(); sum -= n; } } };
function combinationSum(candidates: number[], target: number): number[][] { const resArr: number[][] = []; function backTracking( candidates: number[], target: number, startIndex: number, route: number[], curSum: number ): void { if (curSum > target) return; if (curSum === target) { resArr.push(route.slice()); return } for (let i = startIndex, length = candidates.length; i < length; i++) { let tempVal: number = candidates[i]; route.push(tempVal); backTracking(candidates, target, i, route, curSum + tempVal); route.pop(); } } backTracking(candidates, target, 0, [], 0); return resArr; };
impl Solution { pub fn backtracking(result: &mut Vec<Vec<i32>>, path: &mut Vec<i32>, candidates: &Vec<i32>, target: i32, mut sum: i32, start_index: usize) { if sum == target { result.push(path.to_vec()); return; } for i in start_index..candidates.len() { if sum + candidates[i] <= target { sum += candidates[i]; path.push(candidates[i]); Self::backtracking(result, path, candidates, target, sum, i); sum -= candidates[i]; path.pop(); } } } pub fn combination_sum(candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> { let mut result: Vec<Vec<i32>> = Vec::new(); let mut path: Vec<i32> = Vec::new(); Self::backtracking(&mut result, &mut path, &candidates, target, 0, 0); result } }
int* path; int pathTop; int** ans; int ansTop; //记录每一个和等于target的path数组长度 int* length; void backTracking(int target, int index, int* candidates, int candidatesSize, int sum) { //若sum>=target就应该终止遍历 if(sum >= target) { //若sum等于target,将当前的组合放入ans数组中 if(sum == target) { int* tempPath = (int*)malloc(sizeof(int) * pathTop); int j; for(j = 0; j < pathTop; j++) { tempPath[j] = path[j]; } ans[ansTop] = tempPath; length[ansTop++] = pathTop; } return ; } int i; for(i = index; i < candidatesSize; i++) { //将当前数字大小加入sum sum+=candidates[i]; path[pathTop++] = candidates[i]; backTracking(target, i, candidates, candidatesSize, sum); sum-=candidates[i]; pathTop--; } } int** combinationSum(int* candidates, int candidatesSize, int target, int* returnSize, int** returnColumnSizes){ //初始化变量 path = (int*)malloc(sizeof(int) * 50); ans = (int**)malloc(sizeof(int*) * 200); length = (int*)malloc(sizeof(int) * 200); ansTop = pathTop = 0; backTracking(target, 0, candidates, candidatesSize, 0); //设置返回的数组大小 *returnSize = ansTop; *returnColumnSizes = (int*)malloc(sizeof(int) * ansTop); int i; for(i = 0; i < ansTop; i++) { (*returnColumnSizes)[i] = length[i]; } return ans; }
func combinationSum(_ candidates: [Int], _ target: Int) -> [[Int]] { var result = [[Int]]() var path = [Int]() func backtracking(sum: Int, startIndex: Int) { // 终止条件 if sum == target { result.append(path) return } let end = candidates.count guard startIndex < end else { return } for i in startIndex ..< end { let sum = sum + candidates[i] // 使用局部变量隐藏回溯 if sum > target { continue } // 剪枝 path.append(candidates[i]) // 处理 backtracking(sum: sum, startIndex: i) // i不用+1以重复访问 path.removeLast() // 回溯 } } backtracking(sum: 0, startIndex: 0) return result }
object Solution { import scala.collection.mutable def combinationSum(candidates: Array[Int], target: Int): List[List[Int]] = { var result = mutable.ListBuffer[List[Int]]() var path = mutable.ListBuffer[Int]() def backtracking(sum: Int, index: Int): Unit = { if (sum == target) { result.append(path.toList) // 如果正好等于target,就添加到结果集 return } // 应该是从当前索引开始的,而不是从0 // 剪枝优化:添加循环守卫,当sum + c(i) <= target的时候才循环,才可以进入下一次递归 for (i <- index until candidates.size if sum + candidates(i) <= target) { path.append(candidates(i)) backtracking(sum + candidates(i), i) path = path.take(path.size - 1) } } backtracking(0, 0) result.toList } }
public class Solution { public IList<IList<int>> res = new List<IList<int>>(); public IList<int> path = new List<int>(); public IList<IList<int>> CombinationSum(int[] candidates, int target) { BackTracking(candidates, target, 0, 0); return res; } public void BackTracking(int[] candidates, int target, int start, int sum) { if (sum > target) return; if (sum == target) { res.Add(new List<int>(path)); return; } for (int i = start; i < candidates.Length; i++) { sum += candidates[i]; path.Add(candidates[i]); BackTracking(candidates, target, i, sum); sum -= candidates[i]; path.RemoveAt(path.Count - 1); } } } // 剪枝优化 public class Solution { public IList<IList<int>> res = new List<IList<int>>(); public IList<int> path = new List<int>(); public IList<IList<int>> CombinationSum(int[] candidates, int target) { Array.Sort(candidates); BackTracking(candidates, target, 0, 0); return res; } public void BackTracking(int[] candidates, int target, int start, int sum) { if (sum > target) return; if (sum == target) { res.Add(new List<int>(path)); return; } for (int i = start; i < candidates.Length && sum + candidates[i] <= target; i++) { sum += candidates[i]; path.Add(candidates[i]); BackTracking(candidates, target, i, sum); sum -= candidates[i]; path.RemoveAt(path.Count - 1); } } }