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
| var combinationSum2 = function (candidates, target) { candidates.sort((a, b) => a - b);
const res = []; const visited = new Array(candidates.length).fill(false); const backTracking = function (index, path, sum) { if (index > candidates.length) { return; } if (sum === target) { return res.push(path); } if (sum > target) { return; } for ( let i = index; i < candidates.length && candidates[i] + sum <= target; i++ ) { if (i > 0 && candidates[i] === candidates[i - 1] && !visited[i - 1]) { continue; } visited[i] = true; backTracking(i + 1, [...path, candidates[i]], sum + candidates[i]); visited[i] = false; } }; backTracking(0, [], 0); return res; };
|