I was trying to solve the following problem using backtracking :
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.
Here is my attempt:
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)
);
};
Input
const array = [1, 3, 4];
const index = 0;
const sum = 5;
Output
[ 1, 1, 1, 1, 1 ]
[ 1, 1, 3 ]
[ 1, 4 ]
3
As you can see the output there are only half the number of combinations.
The missing combinations are :
[ 1, 3, 1 ]
[ 3,1,1]
[ 4, 1 ]
I can reason out as to why this is the case since my right subtree is called is constructed using backtrack(array, index + 1, result, sum)
which looks for elements with index greater than the current one. Could anyone possibly give me hints about the changes I need to make in order to achieve the desired output?
Try this:
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;
};
You have to iterate over the whole array, when defining the first element of the resulting list.