For example an input of 3 would return [1,1,1], [2,1], and [1,2]
I know a lot of combination/permutation problems involve a recursive function that calls itself inside of a loop but I’m unable to see an appropriate way to apply it to this problem.
It’s a concept I’m trying to grasp, here’s what I have so far…
function numberToAddends($number, $arr, $k){
for ($i = 0; $i < $number; $i++) {
$arr[$k] = $i;
numberToAddends($k-$i, $arr, $k + 1);
}
if($k <=0){
print_r($arr);
}
}
For test input, you can use something like numberToAddends(3, $arr, 0);
Am I thinking along the right path? Can anyone provide complete php syntax to solve this problem along with commented code?
Here’s an algorithm that solves this problem by reusing the sub-result from 1 to n:
This builds the result set for x by combining any already known result z for any y < x with the difference of x and y and finally x itself.