List all the ways that 1, 2, and 3 can add up to 4, the order matters. For example, [1, 1, 1, 1]
is one way. [1,1,2]
is different from [1,2,1]
I have figured out one way it works on paper. But I still cannot write the code for it. Please help and Please check out this picture of My Idea for clarity.
This code I wrote failed. But this is how far I've got.
function theseAddToSum(steps = [], sum) {
let results = [];
if (steps.length < 1) return 'error'
for (let i = 0; i < steps.length; i++) {
let cur = steps[i];
let remaining = sum - cur;
if (remaining >= 0) {
console.log('sum', sum, 'step', cur)
let c = theseAddToSum(steps, remaining)
}
}
return results
}
console.log(theseAddToSum([1, 2, 3], 4))
As I console.log('sum', sum, 'step', cur)
, I get the desired results:
sum 4 step 1
sum 3 step 1
sum 2 step 1
sum 1 step 1
sum 2 step 2
sum 3 step 2
sum 1 step 1
sum 3 step 3
sum 4 step 2
sum 2 step 1
sum 1 step 1
sum 2 step 2
sum 4 step 3
sum 1 step 1
My problem is that I don't know how to push the result to results
array. It should look like [[1,1,1,1], [1,1,2], [1,2,1], [1,3], [2,1,1], and on]