36 lines
963 B
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
const combinationSum = function (candidates, target) {
};
/*
利用回溯算法解决每一次都尝试从candidates的当前位置开始向后依次加入path。
如果path中所有值的和等于target就收集结果
如果大于就回溯尝试下一个元素直到把结果收集完毕返回result。
*/
function f1(candidates, target) {
const result = [];
// 回溯函数增加一个 start 参数,用于控制递归选择的起始位置
const backtrack = (start, path, sum) => {
if (sum > target) return;
if (sum === target) {
result.push([...path]);
return;
}
for (let i = start; i < candidates.length; i++) {
path.push(candidates[i]);
backtrack(i, path, sum + candidates[i]); // 允许重复选当前数,所以递归从 i 开始
path.pop();
}
};
backtrack(0, [], 0);
return result;
}