I have an array which is N ints long and I have an input int X. I need to populate whole array with combination of ints whose sum gives X. I need to find all possible combinations, the order matters and the array has fixed length (const N). For example if X=3 and N=4 I need to get this:
[3, 0, 0, 0]
[2, 1, 0, 0]
[2, 0, 1, 0]
[2, 0, 0, 1]
[1, 2, 0, 0]
[1, 1, 1, 0]
[1, 1, 0, 1]
[1, 0, 2, 0]
[1, 0, 1, 1]
[1, 0, 0, 2]
[0, 3, 0, 0]
[0, 2, 1, 0]
[0, 2, 0, 1]
[0, 1, 2, 0]
[0, 1, 1, 1]
[0, 1, 0, 2]
[0, 0, 3, 0]
[0, 0, 2, 1]
[0, 0, 1, 2]
[0, 0, 0, 3]
Moreover I don't want to store all possible combinations in memory but I need to get these values one by one. For example when I called a method NEXT last time I got [0, 2, 0, 1]. When I call it again I need to get next combination [0, 1, 2, 0]. When I call it again I need to get [0, 1, 1, 1] and so on. Is there an alorithm that can do that? Thank you