我试图使用回溯来解决以下问题:
Let us say that you are given a number N, you've to find the number of different ways to write it as the sum of 1, 3 and 4.
这是我的尝试:
const backtrack = (array, index, result = [], sum) => {
if (index >= array.length || sum < 0) {
return 0;
}
if (sum === 0) {
console.log(result);
return 1;
}
return (
backtrack(array, index, result.concat(array[index]), sum - array[index]) +
backtrack(array, index + 1, result, sum)
);
};
输入
const array = [1, 3, 4];
const index = 0;
const sum = 5;
输出
[ 1, 1, 1, 1, 1 ]
[ 1, 1, 3 ]
[ 1, 4 ]
3
正如您所看到的输出,组合数量只有一半。
缺少的组合是:
[ 1, 3, 1 ]
[ 3,1,1]
[ 4, 1 ]
我可以推理出为什么会出现这种情况,因为我的右子树是使用 backtrack(array, index + 1, result, sum) 构造的
它查找索引大于当前索引的元素。任何人都可以给我一些关于我需要进行哪些更改才能实现所需输出的提示吗?
最佳答案
试试这个:
backtrack = (array, index, result = [], remainig) => {
if (index >= array.length || remainig < 0) {
return 0;
}
if (remainig === 0) {
console.log(result);
return 1;
}
var sum = 0;
for (var ind = 0; ind < array.length; ind++) {
const curr = array[ind];
sum += backtrack(array, 0, result.concat(curr), remainig - curr);
}
return sum;
};
在定义结果列表的第一个元素时,您必须迭代整个数组。
关于javascript - 使用回溯的子集和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53090340/