Finding all possible combinations of numbers to reach a given sum

前端 未结 30 3105
一个人的身影
一个人的身影 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条回答
  •  -上瘾入骨i
    2020-11-21 06:59

    I did not like the Javascript Solution I saw above. Here is the one I build using partial applying, closures and recursion:

    Ok, I was mainly concern about, if the combinations array could satisfy the target requirement, hopefully this approached you will start to find the rest of combinations

    Here just set the target and pass the combinations array.

    function main() {
        const target = 10
        const getPermutationThatSumT = setTarget(target)
        const permutation = getPermutationThatSumT([1, 4, 2, 5, 6, 7])
    
        console.log( permutation );
    }
    

    the currently implementation I came up with

    function setTarget(target) {
        let partial = [];
    
        return function permute(input) {
            let i, removed;
            for (i = 0; i < input.length; i++) {
                removed = input.splice(i, 1)[0];
                partial.push(removed);
    
                const sum = partial.reduce((a, b) => a + b)
                if (sum === target) return partial.slice()
                if (sum < target) permute(input)
    
                input.splice(i, 0, removed);
                partial.pop();
            }
            return null
        };
    }
    

提交回复
热议问题