Find the highest subset of an integer array whose sums add up to a given target

后端 未结 1 1248
梦毁少年i
梦毁少年i 2020-12-11 14:02

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

相关标签:
1条回答
  • 2020-12-11 14:20

    The basic pattern for recursion is:

    1. Return known value for simple case(s). For this problem, the simple cases are (a) a target of 0 (solution is the empty array) and (b) a negative target (failure).
    2. Recurse and return some calculation based on the answer. For this problem, we look at each candidate value, and recurse with a target reduced by that value, returning an array composed of the result of the recursion with the addition of the current element.

    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]
    
    0 讨论(0)
提交回复
热议问题