Algorithms first
组合总和 · 交互式算法学习
找出可重复选择元素、总和为 target 的组合。
#39 · 回溯
组合总和
Combination Sum
candidates = [2,3,6,7], target = 7递归树3 个关键状态
步骤 1选择 2,remain 变 5。
path=[2]推荐
有序起点剪枝回溯
时间
指数级空间 O(target/min)下一层只从当前下标继续选,避免排列重复;排序后可提前停止。
1function combinationSum(a, t) {2 a.sort((x, y) => x - y);3 const out = [];4 5 function dfs(start, remain, path) {6 if (remain === 0) {7 out.push([...path]);8 return9 }10 for (let i = start; i < a.length && a[i] <= remain; i++) {11 path.push(a[i]);12 dfs(i, remain - a[i], path);13 path.pop()14 }15 }16 dfs(0, t, []);17 return out;18}多语言参考
来源 · CC BY-SA 4.0 ↗Java · C++ · Go
这是一组同题正确实现,独立于上方当前动画方法;不同语言可能采用另一种正确策略。
1class Solution {2 private List<List<Integer>> ans = new ArrayList<>();3 private List<Integer> t = new ArrayList<>();4 private int[] candidates;5 6 public List<List<Integer>> combinationSum(int[] candidates, int target) {7 Arrays.sort(candidates);8 this.candidates = candidates;9 dfs(0, target);10 return ans;11 }12 13 private void dfs(int i, int s) {14 if (s == 0) {15 ans.add(new ArrayList(t));16 return;17 }18 if (s < candidates[i]) {19 return;20 }21 for (int j = i; j < candidates.length; ++j) {22 t.add(candidates[j]);23 dfs(j, s - candidates[j]);24 t.remove(t.size() - 1);25 }26 }27}交互式算法学习
从执行步骤真正理解 LeetCode 经典 150
本站整理 150 道高频算法面试题和 302 种解法。动画方法同步展示 JavaScript 与 Python;每题另提供 Java、C++ 与 Go 同题参考实现。
AlgoViz Lab
组合总和 · 解法对比
找出可重复选择元素、总和为 target 的组合。
- 测试用例
candidates = [2,3,6,7], target = 7- 题目分类
- 回溯
- 解法对比
- 2
无序选择回溯 + 集合去重
每层尝试所有数字,命中后把排序组合放集合。
- 时间
指数级- 空间
O(target)
有序起点剪枝回溯
下一层只从当前下标继续选,避免排列重复;排序后可提前停止。
- 时间
指数级- 空间
O(target/min)