var combinationSum = function(candidates, target) { const res = []; constdfs = (start, path, sum) => { if (sum === target) { res.push([...path]); return; } if (sum > target) return;
for (let i = start; i < candidates.length; i++) { path.push(candidates[i]); dfs(i, path, sum + candidates[i]); // 可以重复选 path.pop(); } }; dfs(0, [], 0); return res; };
✅ Swift 实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
funccombinationSum(_candidates: [Int], _target: Int) -> [[Int]] { var res = [[Int]]() funcdfs(_start: Int, _path: [Int], _sum: Int) { if sum == target { res.append(path) return } if sum > target { return } for i in start..<candidates.count { dfs(i, path + [candidates[i]], sum + candidates[i]) } } dfs(0, [], 0) return res }