Open hyunahOh opened 1 year ago
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
let res;
var combinationSum = function(candidates, target) {
res = [];
const backtrack = (sum, selected ,idx) => {
if(sum === target){
res.push(selected);
return;
}
else if(sum > target){
return;
}
for(let i=idx; i<candidates.length;i++){
selected.push(candidates[i]);
sum += candidates[i];
backtrack(sum, [...selected], i);
selected.pop();
sum -= candidates[i];
}
}
backtrack(0, [], 0);
return res;
};
/**
* @param {number[]} candidates
* @param {number} target
* @return {number[][]}
*/
let answer = [];
var combinationSum = function(candidates, target) {
answer = [];
// combination?
const arr = findCombination(candidates, 0, target);
return answer;
};
function findCombination(arr, idx, target, currArr = [], currSum = 0) {
for (let i = idx; i < arr.length; i++) {
const curr = arr[i];
if (currSum === target) {
answer.push(currArr);
break;
} else if (currSum > target) {
continue;
} else if (currSum < target) {
findCombination(arr, i, target, [...currArr, curr], currSum + curr);
}
}
}