LeetCode 40. 组合总和 II 详解:排序 + 剪枝 + 回溯的去重之道
LeetCode 40. 组合总和 II 详解:排序 + 剪枝 + 回溯的去重之道
本篇技术指南以 doocs/leetcode 仓库中 40. 组合总和 II 题解文档 为骨架,深入剖析"候选数字含重复、每个数字只能用一次"约束下的组合搜索问题。读完本文,你将掌握回溯算法中"排序预处理 + 同层去重 + 剩余值剪枝"的完整套路,理解两种经典写法(循环内去重 / 选与不选)的异同,并能在 Python、Java、C++、Go、TypeScript、Rust、JavaScript、C#、PHP 中随手写出可运行的高效实现。
题目理解与约束分析
问题定义
给定一个候选人编号的集合 candidates 和一个目标数 target,找出 candidates 中所有可以使数字和为 target 的组合。与 39. 组合总和 不同,本题有两个关键差异:
candidates中的每个数字在每个组合中只能使用一次;candidates中可能包含重复值,而解集不能包含重复的组合。
示例
示例 1:
输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]
注意示例 1 中 candidates 有两个 1,输出中 [1,1,6] 恰好使用了这两个 1,而 [1,2,5] 与 [1,7] 各自只使用其中一个 1——但由于解集不能重复,最终每种组合只出现一次。
示例 2:
输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]
candidates 中有三个 2,[1,2,2] 只出现一次,而不是按"取哪两个 2"的不同下标组合重复出现三次。
数据范围提示
1 <= candidates.length <= 100
1 <= candidates[i] <= 50
1 <= target <= 30
从提示可见:n 最大 100,target 最大 30。这意味着若不做剪枝,暴力枚举所有子集是 量级,在 n=100 时完全不可行;而 target ≤ 30 给了我们极强的剪枝空间——一旦剩余目标值小于当前候选数字,整支搜索即可终止。这正是"排序 + 剪枝"能高效求解的前提。
核心思路:为什么先排序?
回溯搜索组合类问题的经典范式是:设计递归函数 dfs(i, s),表示从下标 i 开始搜索、剩余目标值为 s,当前已选路径为 t,最终答案为 ans。
排序在这里承担了两个职责:
- 让相同数字相邻,从而支持"同层去重":如果
[1,1,2,2,5,6,7,10]中两个1相邻,在枚举本层选择时,只要发现"当前值与上一个值相同"就可以跳过,因为上一个值已经作为本层选择被完整搜索过; - 让剩余值剪枝成立:排序后数组升序,一旦
s < candidates[i],说明当前及后面所有元素都大于剩余目标值,整支路径不可能再凑出目标,直接返回。
若不排序也不去重,同一组数字会因下标组合不同而被搜索多次,导致大量重复组合出现在答案中。
解法一:排序 + 剪枝 + 回溯(循环内同层去重)
算法流程
设计函数 dfs(i, s),其中 i 和 s 都是非负整数:
- 若
s == 0,说明当前路径t的数字和正好等于target,将t的副本加入答案ans后返回; - 若
i >= n(n为candidates长度)或s < candidates[i],说明剩余元素中最小者都已超过剩余目标,路径不合法,直接返回; - 否则从下标
j = i开始枚举到n - 1:- 若
j > i且candidates[j] == candidates[j - 1],说明该值与上一轮枚举的值相同、已经作为本层选择搜索过,跳过(这是本题去重的关键一行); - 否则将
candidates[j]加入路径t,递归调用dfs(j + 1, s - candidates[j])(注意下标是j + 1,保证每个数字只用一次); - 递归返回后执行
t.pop()撤销选择,恢复现场,继续枚举下一个j。
- 若
主函数中先对 candidates 排序,再调用 dfs(0, target) 即可得到答案。
去重条件的直观含义:j > i 限定"只看本层循环中的相邻重复",而不是跳过与上层(递归更深层)元素相同的值——[1,1,6] 中两个 1 分属不同层,恰好被保留下来。这正是"解集不重复、但同一数值可以在不同层重复出现"的微妙之处。
各语言实现
Python3
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if i >= len(candidates) or s < candidates[i]:
return
for j in range(i, len(candidates)):
if j > i and candidates[j] == candidates[j - 1]:
continue
t.append(candidates[j])
dfs(j + 1, s - candidates[j])
t.pop()
candidates.sort()
ans = []
t = []
dfs(0, target)
return ans
对应仓库文件:Solution.py
Java
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> t = new ArrayList<>();
private int[] candidates;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.add(new ArrayList<>(t));
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
for (int j = i; j < candidates.length; ++j) {
if (j > i && candidates[j] == candidates[j - 1]) {
continue;
}
t.add(candidates[j]);
dfs(j + 1, s - candidates[j]);
t.remove(t.size() - 1);
}
}
}
对应仓库文件:Solution.java
C++
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> t;
function<void(int, int)> dfs = & {
if (s == 0) {
ans.emplace_back(t);
return;
}
if (i >= candidates.size() || s < candidates[i]) {
return;
}
for (int j = i; j < candidates.size(); ++j) {
if (j > i && candidates[j] == candidates[j - 1]) {
continue;
}
t.emplace_back(candidates[j]);
dfs(j + 1, s - candidates[j]);
t.pop_back();
}
};
dfs(0, target);
return ans;
}
};
Go
func combinationSum2(candidates []int, target int) (ans [][]int) {
sort.Ints(candidates)
t := []int{}
var dfs func(i, s int)
dfs = func(i, s int) {
if s == 0 {
ans = append(ans, slices.Clone(t))
return
}
if i >= len(candidates) || s < candidates[i] {
return
}
for j := i; j < len(candidates); j++ {
if j > i && candidates[j] == candidates[j-1] {
continue
}
t = append(t, candidates[j])
dfs(j+1, s-candidates[j])
t = t[:len(t)-1]
}
}
dfs(0, target)
return
}
注意 Go 中 slices.Clone(t) 与 t = t[:len(t)-1] 分别对应"拷贝结果入答案"与"撤销选择",与 Python 的 t[:]、t.pop() 语义一一对应。
TypeScript
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const ans: number[][] = [];
const t: number[] = [];
const dfs = (i: number, s: number) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
for (let j = i; j < candidates.length; j++) {
if (j > i && candidates[j] === candidates[j - 1]) {
continue;
}
t.push(candidates[j]);
dfs(j + 1, s - candidates[j]);
t.pop();
}
};
dfs(0, target);
return ans;
}
Rust
impl Solution {
fn dfs(i: usize, s: i32, candidates: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if s == 0 {
ans.push(t.clone());
return;
}
if i >= candidates.len() || s < candidates[i] {
return;
}
for j in i..candidates.len() {
if j > i && candidates[j] == candidates[j - 1] {
continue;
}
t.push(candidates[j]);
Self::dfs(j + 1, s - candidates[j], candidates, t, ans);
t.pop();
}
}
pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
candidates.sort();
let mut ans = Vec::new();
Self::dfs(0, target, &candidates, &mut vec![], &mut ans);
ans
}
}
JavaScript
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
candidates.sort((a, b) => a - b);
const ans = [];
const t = [];
const dfs = (i, s) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
for (let j = i; j < candidates.length; ++j) {
if (j > i && candidates[j] === candidates[j - 1]) {
continue;
}
t.push(candidates[j]);
dfs(j + 1, s - candidates[j]);
t.pop();
}
};
dfs(0, target);
return ans;
};
C#
public class Solution {
private List<IList<int>> ans = new List<IList<int>>();
private List<int> t = new List<int>();
private int[] candidates;
public IList<IList<int>> CombinationSum2(int[] candidates, int target) {
Array.Sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.Add(new List<int>(t));
return;
}
if (i >= candidates.Length || s < candidates[i]) {
return;
}
for (int j = i; j < candidates.Length; ++j) {
if (j > i && candidates[j] == candidates[j - 1]) {
continue;
}
t.Add(candidates[j]);
dfs(j + 1, s - candidates[j]);
t.RemoveAt(t.Count - 1);
}
}
}
解法二:排序 + 剪枝 + 回溯("选 / 不选"二分写法)
算法流程
方法一把"去重"和"多叉枚举"写在了同一个循环里;方法二则换一种视角:对每个下标,只做两个决策——选当前数字或不选当前数字,从而把去重下沉到"不选"分支:
- 若
s == 0,将路径t加入答案; - 若
i >= n或s < candidates[i],返回; - 记
x = candidates[i]:- 选:
t加入x,递归dfs(i + 1, s - x),返回后t.pop(); - 不选:用
while循环把下标i一次推进到第一个不等于x的位置(即跳过一整段相同的值),再递归dfs(i, s)。
- 选:
"不选"分支跳过整段相同值的原因:既然决定不选 x,那么后面所有与 x 相等的元素也不能选(否则就等价于选了 x 却换了下标,会产生重复组合)。这一写法将去重从"循环内判断"转移为"跳段推进",两种写法的复杂度一致,只是代码结构不同。
各语言实现
Python3
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
def dfs(i: int, s: int):
if s == 0:
ans.append(t[:])
return
if i >= len(candidates) or s < candidates[i]:
return
x = candidates[i]
t.append(x)
dfs(i + 1, s - x)
t.pop()
while i < len(candidates) and candidates[i] == x:
i += 1
dfs(i, s)
candidates.sort()
ans = []
t = []
dfs(0, target)
return ans
对应仓库文件:Solution2.py
Java
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> t = new ArrayList<>();
private int[] candidates;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
Arrays.sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.add(new ArrayList<>(t));
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
int x = candidates[i];
t.add(x);
dfs(i + 1, s - x);
t.remove(t.size() - 1);
while (i < candidates.length && candidates[i] == x) {
++i;
}
dfs(i, s);
}
}
C++
class Solution {
public:
vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
sort(candidates.begin(), candidates.end());
vector<vector<int>> ans;
vector<int> t;
function<void(int, int)> dfs = & {
if (s == 0) {
ans.emplace_back(t);
return;
}
if (i >= candidates.size() || s < candidates[i]) {
return;
}
int x = candidates[i];
t.emplace_back(x);
dfs(i + 1, s - x);
t.pop_back();
while (i < candidates.size() && candidates[i] == x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
}
};
Go
func combinationSum2(candidates []int, target int) (ans [][]int) {
sort.Ints(candidates)
t := []int{}
var dfs func(i, s int)
dfs = func(i, s int) {
if s == 0 {
ans = append(ans, slices.Clone(t))
return
}
if i >= len(candidates) || s < candidates[i] {
return
}
x := candidates[i]
t = append(t, x)
dfs(i+1, s-x)
t = t[:len(t)-1]
for i < len(candidates) && candidates[i] == x {
i++
}
dfs(i, s)
}
dfs(0, target)
return
}
TypeScript
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const ans: number[][] = [];
const t: number[] = [];
const dfs = (i: number, s: number) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
const x = candidates[i];
t.push(x);
dfs(i + 1, s - x);
t.pop();
while (i < candidates.length && candidates[i] === x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
}
Rust
impl Solution {
fn dfs(mut i: usize, s: i32, candidates: &Vec<i32>, t: &mut Vec<i32>, ans: &mut Vec<Vec<i32>>) {
if s == 0 {
ans.push(t.clone());
return;
}
if i >= candidates.len() || s < candidates[i] {
return;
}
let x = candidates[i];
t.push(x);
Self::dfs(i + 1, s - x, candidates, t, ans);
t.pop();
while i < candidates.len() && candidates[i] == x {
i += 1;
}
Self::dfs(i, s, candidates, t, ans);
}
pub fn combination_sum2(mut candidates: Vec<i32>, target: i32) -> Vec<Vec<i32>> {
candidates.sort();
let mut ans = Vec::new();
Self::dfs(0, target, &candidates, &mut vec![], &mut ans);
ans
}
}
JavaScript
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum2 = function (candidates, target) {
candidates.sort((a, b) => a - b);
const ans = [];
const t = [];
const dfs = (i, s) => {
if (s === 0) {
ans.push(t.slice());
return;
}
if (i >= candidates.length || s < candidates[i]) {
return;
}
const x = candidates[i];
t.push(x);
dfs(i + 1, s - x);
t.pop();
while (i < candidates.length && candidates[i] === x) {
++i;
}
dfs(i, s);
};
dfs(0, target);
return ans;
};
C#
public class Solution {
private List<IList<int>> ans = new List<IList<int>>();
private List<int> t = new List<int>();
private int[] candidates;
public IList<IList<int>> CombinationSum2(int[] candidates, int target) {
Array.Sort(candidates);
this.candidates = candidates;
dfs(0, target);
return ans;
}
private void dfs(int i, int s) {
if (s == 0) {
ans.Add(new List<int>(t));
return;
}
if (i >= candidates.Length || s < candidates[i]) {
return;
}
int x = candidates[i];
t.Add(x);
dfs(i + 1, s - x);
t.RemoveAt(t.Count - 1);
while (i < candidates.Length && candidates[i] == x) {
++i;
}
dfs(i, s);
}
}
PHP
class Solution {
/**
* @param integer[] $candidates
* @param integer $target
* @return integer[][]
*/
function combinationSum2($candidates, $target) {
$result = [];
$currentCombination = [];
$startIndex = 0;
sort($candidates);
$this->findCombinations($candidates, $target, $startIndex, $currentCombination, $result);
return $result;
}
function findCombinations($candidates, $target, $startIndex, $currentCombination, &$result) {
if ($target === 0) {
$result[] = $currentCombination;
return;
}
for ($i = $startIndex; $i < count($candidates); $i++) {
$num = $candidates[$i];
if ($num > $target) {
break;
}
if ($i > $startIndex && $candidates[$i] === $candidates[$i - 1]) {
continue;
}
$currentCombination[] = $num;
$this->findCombinations(
$candidates,
$target - $num,
$i + 1,
$currentCombination,
$result,
);
array_pop($currentCombination);
}
}
}
PHP 实现本质上与方法一同构:$num > $target 时 break(对应排序后剩余值剪枝),$i > $startIndex && $candidates[$i] === $candidates[$i - 1] 时 continue(同层去重),递归下标 $i + 1 保证每个数字只用一次。
复杂度分析
| 维度 | 上界 | 说明 |
|---|---|---|
| 时间复杂度 | 最坏情况下每个元素都有"选/不选"两种分支,每得到一个合法组合需要 拷贝路径;但由于剪枝(剩余值小于当前元素即停止),实际运行时间远小于上界 | |
| 空间复杂度 | 递归深度最多为 n,路径数组 t 的长度不超过 n |
两种写法的复杂度完全相同。需要强调的是,target ≤ 30 的约束在剪枝中作用显著:搜索树中大量分支会因"剩余值不足以选取更大元素"而提前终止,这也是本题在 n = 100 时依然可解的根本原因。
两种写法对比:去重位置的不同哲学
| 对比维度 | 解法一(循环内去重) | 解法二(选 / 不选) |
|---|---|---|
| 枚举结构 | 每层一个 for 循环,多叉展开 |
每个节点固定"选 / 不选"两个分支 |
| 去重方式 | j > i && candidates[j] == candidates[j - 1] 跳过同层相邻重复 |
不选分支 while 跳段推进到第一个不同值 |
| 递归下标 | dfs(j + 1, s - candidates[j]) |
选:dfs(i + 1, s - x);不选:dfs(跳过整段后的 i, s) |
| 适用场景 | 更贴近"组合枚举"直觉,代码紧凑 | 更贴近"子集/01 决策"思维,便于扩展到其他选/不选问题 |
两者在结果上完全等价,选哪种取决于个人习惯。理解两种写法,有助于你从"去重到底发生在哪个环节"的层面真正吃透回溯算法。
相似题目串联:组合类回溯题单
本题在仓库中归属于"组合"回溯系列,与以下题目共享"排序 + 剪枝 + 回溯"的解题范式,建议按顺序练习:
- 39. 组合总和:候选无重复、每个数字可无限次使用,递归下标保持
j而不是j + 1; - 40. 组合总和 II:候选含重复、每个数字只能用一次,需要同层去重(本题);
- 77. 组合:固定选取
k个元素,无需求和剪枝,只需长度剪枝; - 216. 组合总和 III:限定
1~9中选k个数和为n,是 77 与 39 的融合变体。
一个快速记忆法:"可重复用"递归下标不变,"不可重复用"递归下标加一;"候选含重复"必须排序后同层去重。掌握了这一规则,组合类回溯题基本可以一网打尽。
小结
本题是回溯算法中"去重"的典型考题,其要点可归纳为三条:
- 先排序:让相同数字相邻,是"同层去重"和"剩余值剪枝"共同的前提;
- 剪枝:
s < candidates[i]时整支停止,利用target ≤ 30的约束大幅压缩搜索空间; - 去重:解法一在循环内跳过
j > i的相邻重复值,解法二在"不选"分支跳段推进——两种写法殊途同归,均保证每个组合只输出一次。
完整的双语题解与多语言源码均可在仓库对应目录查看:README.md 与 README_EN.md(含全部 9 种语言实现),独立的可运行源码见 Solution.py、Solution.java 等 Solution* 系列文件。