From ece55fe7efe84e4a76e1fd35d3046dd1aa67f2b5 Mon Sep 17 00:00:00 2001 From: "qingyi.liu" Date: Sat, 5 Jun 2021 18:44:08 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A040.=E7=BB=84=E5=90=88?= =?UTF-8?q?=E6=80=BB=E5=92=8CIIJavaScript=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0040.组合总和II.md | 34 ++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/problems/0040.组合总和II.md b/problems/0040.组合总和II.md index 4d2996f5..a462b524 100644 --- a/problems/0040.组合总和II.md +++ b/problems/0040.组合总和II.md @@ -293,7 +293,7 @@ class Solution { } ``` Python: -```python3 +```py class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: res = [] @@ -314,7 +314,39 @@ class Solution: ``` Go: +javaScript: +```js +/** + * @param {number[]} candidates + * @param {number} target + * @return {number[][]} + */ +var combinationSum2 = function(candidates, target) { + const res = []; path = [], len = candidates.length; + candidates.sort(); + backtracking(0, 0); + return res; + function backtracking(sum, i) { + if (sum > target) return; + if (sum === target) { + res.push(Array.from(path)); + return; + } + let f = -1; + for(let j = i; j < len; j++) { + const n = candidates[j]; + if(n > target - sum || n === f) continue; + path.push(n); + sum += n; + f = n; + backtracking(sum, j + 1); + path.pop(); + sum -= n; + } + } +}; +``` -----------------------