Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3041
一个人的身影
一个人的身影 2020-11-21 06:39

How would you go about testing all possible combinations of additions from a given set N of numbers so they add up to a given final number?

A brief exam

30条回答
  •  无人共我
    2020-11-21 07:14

    Perl version (of the leading answer):

    use strict;
    
    sub subset_sum {
      my ($numbers, $target, $result, $sum) = @_;
    
      print 'sum('.join(',', @$result).") = $target\n" if $sum == $target;
      return if $sum >= $target;
    
      subset_sum([@$numbers[$_ + 1 .. $#$numbers]], $target, 
                 [@{$result||[]}, $numbers->[$_]], $sum + $numbers->[$_])
        for (0 .. $#$numbers);
    }
    
    subset_sum([3,9,8,4,5,7,10,6], 15);
    

    Result:

    sum(3,8,4) = 15
    sum(3,5,7) = 15
    sum(9,6) = 15
    sum(8,7) = 15
    sum(4,5,6) = 15
    sum(5,10) = 15
    

    Javascript version:

    const subsetSum = (numbers, target, partial = [], sum = 0) => {
      if (sum < target)
        numbers.forEach((num, i) =>
          subsetSum(numbers.slice(i + 1), target, partial.concat([num]), sum + num));
      else if (sum == target)
        console.log('sum(%s) = %s', partial.join(), target);
    }
    
    subsetSum([3,9,8,4,5,7,10,6], 15);

    Javascript one-liner that actually returns results (instead of printing it):

    const subsetSum=(n,t,p=[],s=0,r=[])=>(ssubsetSum(n.slice(i+1),t,[...p,l],s+l,r)):s==t?r.push(p):0,r);
    
    console.log(subsetSum([3,9,8,4,5,7,10,6], 15));

    And my favorite, one-liner with callback:

    const subsetSum=(n,t,cb,p=[],s=0)=>ssubsetSum(n.slice(i+1),t,cb,[...p,l],s+l)):s==t?cb(p):0;
    
    subsetSum([3,9,8,4,5,7,10,6], 15, console.log);

提交回复
热议问题