40.组合总和II
链接:40.组合总和II
难度:Medium
标签:数组、回溯
简介:给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
题解 1 - typescript
- 编辑时间:2020-09-10
- 执行用时:88ms
- 内存消耗:39.7MB
- 编程语言:typescript
- 解法介绍:遍历数组递归。
function combinationSum2(candidates: number[], target: number): number[][] {
candidates.sort((a, b) => a - b);
const len = candidates.length;
const res: number[][] = [];
dfs();
return res;
function dfs(start = 0, temp: number[] = [], sum = 0) {
if (sum === target) res.push(temp.slice());
else if (sum > target) {
} else {
for (let i = start; i < len; i++) {
const num = candidates[i];
if (candidates[i - 1] === num && i - 1 >= start) continue;
temp.push(num);
dfs(i + 1, temp, sum + num);
temp.pop();
}
}
}
}