Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Backtracking algorithm of finding all possible combination #50

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
253 changes: 252 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

35 changes: 33 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,41 @@
* @param {number} startFrom - index of the candidate to start further exploration from.
* @return {number[][]}
*/

/** if you want to test the function combinationSumRecursive
* I suggest to copy code from line 10 to line 40 and able debugger in line 28
*/
const combinationSumRecursive = (
candidates,
remainingSum,
finalCombinations =[],
currentCombination =[],
startFrom = 0,
)=>{
if (remainingSum ===0){
finalCombinations.push(currentCombination.slice());
}

if(remainingSum < 0) {
return finalCombinations;
}

for (let i= startFrom; i < candidates.length; i++){
//debugger
const current = candidates[i];
currentCombination.push(current);

//add the next position of the array candidates and try again until remainingSum < 0
combinationSumRecursive(candidates, remainingSum - current, finalCombinations,currentCombination, i);

//delete candidate
currentCombination.pop();



}
return finalCombinations

}
}

/**
* Backtracking algorithm of finding all possible combination for specific sum.
Expand Down