I am trying to find a subset of values within an array which add up to a given number and return an array of that subset. I need the return array to contain the highest poss
The basic pattern for recursion is:
So:
// Find subset of a that sums to n.
function subset_sum(n, a) {
// SIMPLE CASES
if (n < 0) return null; // Nothing adds up to a negative number
if (n === 0) return []; // Empty list is the solution for a target of 0
// RECURSIVE CASE
a = a.slice();
while (a.length) { // Try remaining values
var v = a.shift(); // Take next value
var s = subset_sum(n - v, a); // Find solution recursively
if (s) return s.concat(v); // If solution, return
}
}
To enforce the rule that you want to prefer higher values first, pass this function an array of values that is pre-sorted in descending order.
> subset_sum(19, [11, 9, 7, 5, 3, 2, 1])
< [1, 7, 11]