Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Creating permutations to reach a target number, but reuse the provided numbers JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a target sum Number as the second argument.
The function should return an array of all those subarrays from the original array whose elements sum to make the target sum. We can use a single number multiple times to achieve the sum.
For example −
If the input array and number are −
const arr = [1, 2, 4]; const sum = 4;
then the output should be −
[ [1, 1, 1, 1], [1, 1, 2], [2, 2], [4] ]
Solution
We'll use a recursive approach with backtracking to find all combinations. The algorithm explores each element multiple times until the sum exceeds the target or equals it.
const arr = [1, 2, 4];
const sum = 4;
const getCombinations = (arr = [], sum) => {
const result = [];
const pushElement = (i, t) => {
const currentSum = t.reduce(function (a, b) {
return a + b;
}, 0);
if (sum === currentSum) {
result.push(t);
return;
}
if (currentSum > sum || i === arr.length) {
return;
}
// Include current element (can be used multiple times)
pushElement(i, t.concat([arr[i]]));
// Move to next element
pushElement(i + 1, t);
}
pushElement(0, []);
return result;
};
console.log(getCombinations(arr, sum));
[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]
How It Works
The recursive function pushElement takes two parameters:
- i: Current index in the array
- t: Current combination being built
For each element, we have two choices:
- Include the current element (stay at same index to allow reuse)
- Skip to the next element
The recursion stops when either the sum equals the target (success) or exceeds it (failure).
Alternative Implementation
Here's a cleaner version using modern JavaScript syntax:
const findCombinations = (nums, target) => {
const result = [];
const backtrack = (index, current, currentSum) => {
if (currentSum === target) {
result.push([...current]);
return;
}
if (currentSum > target || index >= nums.length) {
return;
}
// Include current number
current.push(nums[index]);
backtrack(index, current, currentSum + nums[index]);
current.pop();
// Skip to next number
backtrack(index + 1, current, currentSum);
};
backtrack(0, [], 0);
return result;
};
const numbers = [1, 2, 4];
const targetSum = 4;
console.log(findCombinations(numbers, targetSum));
[ [ 1, 1, 1, 1 ], [ 1, 1, 2 ], [ 2, 2 ], [ 4 ] ]
Conclusion
Both approaches use recursive backtracking to generate all valid combinations. The key insight is allowing reuse of elements by staying at the same index when including an element, which enables finding permutations like [1, 1, 1, 1] from the array [1, 2, 4].
