Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3037
一个人的身影
一个人的身影 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:13

    Deduce 0 in the first place. Zero is an identiy for addition so it is useless by the monoid laws in this particular case. Also deduce negative numbers as well if you want to climb up to a positive number. Otherwise you would also need subtraction operation.

    So... the fastest algorithm you can get on this particular job is as follows given in JS.

    function items2T([n,...ns],t){
        var c = ~~(t/n);
        return ns.length ? Array(c+1).fill()
                                     .reduce((r,_,i) => r.concat(items2T(ns, t-n*i).map(s => Array(i).fill(n).concat(s))),[])
                         : t % n ? []
                                 : [Array(c).fill(n)];
    };
    
    var data = [3, 9, 8, 4, 5, 7, 10],
        result;
    
    console.time("combos");
    result = items2T(data, 15);
    console.timeEnd("combos");
    console.log(JSON.stringify(result));

    This is a very fast algorithm but if you sort the data array descending it will be even faster. Using .sort() is insignificant since the algorithm will end up with much less recursive invocations.

提交回复
热议问题