Combination Sum in TypeScript

function combinationSum(candidates: number[], target: number): number[][] {
    let result: number[][] = [];
    let currentCombination: number[] = [];

    function findCombinations(startIndex: number, remainingTarget: number) {
        if (remainingTarget === 0) {
            result.push([...currentCombination]);
            return;
        }

        for (let i = startIndex; i < candidates.length; i++) {
            if (candidates[i] > remainingTarget) {
                // If the candidate is greater than the remaining target, skip it
                continue;
            }

            // Include the candidate in the current combination
            currentCombination.push(candidates[i]);

            // Recurse with the updated remaining target
            findCombinations(i, remainingTarget - candidates[i]);

            // Backtrack: remove the last element added
            currentCombination.pop();
        }
    }

    findCombinations(0, target);
    return result;
}

PrevNext