Find possible numbers in array that can sum to a target value

前端 未结 2 1116
孤独总比滥情好
孤独总比滥情好 2021-01-20 14:59

Given I have an array of numbers for example [14,6,10] - How can I find possible combinations/pairs that can add upto a given target value.

for example I have

2条回答
  •  囚心锁ツ
    2021-01-20 15:49

    You could add the value of the actual index as long as the sum is smaller than the wanted sum or proceed with the next index.

    function getSum(array, sum) {
        function iter(index, temp) {
            var s = temp.reduce((a, b) => a + b, 0);
            if (s === sum) result.push(temp);
            if (s >= sum || index >= array.length) return;
            iter(index, temp.concat(array[index]));
            iter(index + 1, temp);
        }
    
        var result = [];
        iter(0, []);
        return result;
    }
    
    console.log(getSum([14, 6, 10], 40));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

    For getting a limited result set, you could specify the length and check it in the exit condition.

    function getSum(array, sum, limit) {
        function iter(index, temp) {
            var s = temp.reduce((a, b) => a + b, 0);
            if (s === sum) result.push(temp);
            if (s >= sum || index >= array.length || temp.length >= limit) return;
            iter(index, temp.concat(array[index]));
            iter(index + 1, temp);
        }
    
        var result = [];
        iter(0, []);
        return result;
    }
    
    console.log(getSum([14, 6, 10], 40, 5));
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题