
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Combination sum problem using JavaScript
Suppose we are given a set of candidate numbers (without duplicates) and a target number (target).
We are required to write a function that finds all unique combinations in candidates where the candidate numbers sum to the target.
The same repeated number may be chosen from candidates an unlimited number of times.
Note −
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example −
If the inputs are −
candidates = [2,3,6,7], target = 7,
The solution to this can be −
[ [7], [2,2,3] ];
Since the problem is to get all the possible results, not the best or the number of results, thus we don’t need to consider Dynamic Programming, backtracking approach using recursion is needed to handle it.
Example
Following is the code −
const recursiveSum = ( candidates, remainingSum, finalCombinations = [], currentCombination = [], startFrom = 0, ) => { if (remainingSum < 0) { return finalCombinations; } if (remainingSum === 0) { finalCombinations.push(currentCombination.slice()); return finalCombinations; } for (let candidateIndex = startFrom; candidateIndex < candidates.length; candidateIndex += 1) { const currentCandidate = candidates[candidateIndex]; currentCombination.push(currentCandidate); recursiveSum( candidates, remainingSum - currentCandidate, finalCombinations, currentCombination, candidateIndex, ); currentCombination.pop(); } return finalCombinations; } const combinationSum = (candidates, target) => recursiveSum(candidates, target); console.log(combinationSum([2, 3, 6, 7], 7));
Output
Following is the output on console −
[ [ 2, 2, 3 ], [ 7 ] ]
- Related Questions & Answers
- Combination Sum in Python
- Subset Sum Problem
- Combination Sum IIII in C++
- Combination Sum II in C++
- Combination Sum IV in C++
- Two sum problem in linear time in JavaScript
- Substring combination in JavaScript
- How to find the unique combination k sum that corresponds to k sum using C#?
- Python Program for Subset Sum Problem
- Snail Trail Problem in JavaScript
- Recursive Staircase problem in JavaScript
- Distributing Bananas Problem in JavaScript
- Producer Consumer Problem using Semaphores
- Problem Can we fit remaining passengers in the bus using JavaScript
- Recursion problem Snail Trail in JavaScript