From 0d442b3b7bdde1dd81576778efaeb758946c8f6c Mon Sep 17 00:00:00 2001 From: mengyuan Date: Tue, 7 Dec 2021 21:42:05 +0800 Subject: [PATCH] =?UTF-8?q?update:=200040.=E7=BB=84=E5=90=88=E6=80=BB?= =?UTF-8?q?=E5=92=8CII=20JS=E7=89=88=E6=9C=AC=E5=A2=9E=E5=8A=A0=E4=BD=BF?= =?UTF-8?q?=E7=94=A8used=E5=8E=BB=E9=87=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index bab4bd6a..b5e511e7 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -457,6 +457,37 @@ var combinationSum2 = function(candidates, target) { } }; ``` +**使用used去重** +```js +var combinationSum2 = function(candidates, target) { + let res = []; + let path = []; + let total = 0; + const len = candidates.length; + candidates.sort((a, b) => a - b); + let used = new Array(len).fill(false); + const backtracking = (startIndex) => { + if (total === target) { + res.push([...path]); + return; + } + for(let i = startIndex; i < len && total < target; i++) { + const cur = candidates[i]; + if (cur > target - total || (i > 0 && cur === candidates[i - 1] && !used[i - 1])) continue; + path.push(cur); + total += cur; + used[i] = true; + backtracking(i + 1); + path.pop(); + total -= cur; + used[i] = false; + } + } + backtracking(0); + return res; +}; +``` + ## C ```c