Codog

关注微信公众号:Codog代码狗

0%

LeetCode-39-组合总和

给定一个无重复元素的正整数数组 candidates 和一个正整数 target ,找出 candidates 中所有可以使数字和为目标数 target 的唯一组合。

题目描述:
image

思路:递归

大致思路是用target减数组里的值,在用这个差值做下一次递归,并缓存当前的数组的候选值。终止条件为差为0,则为一个有效的结果。如果小于0则忽略,大于0则继续递归。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
var combinationSum = function(candidates, target) {
const queue = [
{
curTarget: target,
curRes: [],
idx: 0
}
]
const len = candidates.length;
const res = []
while(queue.length) {
const { curTarget, curRes, idx } = queue.shift();
for (let i = idx; i < len; i++) {
let t = curTarget - candidates[i];
if (t === 0) {
res.push([...curRes, candidates[i]])
} else if (t > 0) {
queue.push({
curTarget: t,
curRes: [...curRes, candidates[i]],
// 下次继续递减当前索引
idx: i
})
}
}
}
return res
};