[英]Subset sum with recursion - what am I doing wrong?
I am trying to solve this problem to practice thinking recursively: given a target number and an array of numbers, find out if there is a combination of the array elements that sums up to the target number. 我试图解决这个问题,以递归方式练习思考:给定一个目标数字和一个数字数组,找出是否有一个数组元素的组合,总计达到目标数字。 I'm new to this and I have tried everything that I can think of.
我是新手,我已经尝试了所有我能想到的东西。 Is there a problem with my logic or am I forgetting something simple?
我的逻辑有问题还是我忘了简单的事情? Here is my code:
这是我的代码:
function findSolution(target, arr){
function getSum(total, num) {
return total + num;
}
function find(current, push, target, i){
current.push(push);
if (current.reduce(getSum) === target){
return true;
} else if (current.length >= arr.length){
return null;
} else {
return find(current, arr[i], target, i+1) ||
find(current, 0, target, i+1);
}
}
return find([], 0, target, 0);
return false;
}
console.log(findSolution(23, [4, 6, 10, 1, 3] ));
The above target and array should return true (4+6+10+3) but it is returning null. 上面的目标和数组应返回true(4 + 6 + 10 + 3),但它返回null。 Thank you very much for you help :)
非常感谢你的帮助:)
You need to take a copy of current
and you need to return the array with the values. 您需要获取
current
的副本,并且需要使用值返回数组。 Unfortunately, you add too much zeros to the result set. 不幸的是,你在结果集中添加了太多的零。
Therefore I suggest to add a value at the place of calling the function find
. 因此我建议在调用函数
find
的位置添加一个值。
You could omit target
in find
, because you have already a closure over it. 你可以在
find
省略target
,因为你已经有了一个闭包。
function findSolution(target, arr) { function getSum(total, num) { return total + num; } function find(current, i) { if (current.reduce(getSum, 0) === target) { // initialValue for empty arrays return current; } if (i >= arr.length) { return null; } return find(current.concat(arr[i]), i + 1) || find(current, i + 1); } return find([], 0); } console.log(findSolution(23, [4, 6, 10, 1, 3]));
You need to calculate all possible combinations of the value array to find all solutions: 您需要计算值数组的所有可能组合以查找所有解决方案:
function findSolution(target, arr) { const combinations = set => set.reduce( (subsets, value) => [ ...subsets, ...subsets.map(subset => [value, ...subset]) ], [ [] ] ) const getSum = (total, num) => total + num return combinations(arr).find(current => current.reduce(getSum, 0) === target ) } console.log(findSolution(23, [4, 6, 10, 1, 3]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.