Answers for "Combinatorial summation problem"

0

Combinatorial summation problem

var targetArray = function(nums, target) {
    var res = [];
    var dfs = function(path,start) {
        if(sum(path) === target) {                  //(1)
            res.push([...path]);
            return;
        }
        if(sum(path) > target) {
            return;
        }
        for(let i=start; i<nums.length; i++) {     //(2)
            path.push(nums[i]);                    //(3)
            dfs(path.slice(), i);
            path.pop();
        }
    }
    dfs([],0)
    return res;
}
function sum(arr) {
    if(arr.length===0)
        return 0;
    return arr.reduce((a,b)=>a+b)
}

console.log(targetArray([2,3,5],8))
// [ [ 2, 2, 2, 2 ], [ 2, 3, 3 ], [ 3, 5 ] ]
Posted by: Guest on October-29-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language