I'm writing this function which I want to print all the sublists of a given list with integers. The sum of these integers should be equal to a given number n
. There is also a help variable i
which starts with value 0. Both the list and each sublist are an ArrayList
. So the method looks like this right now:
public static void printSublists(ArrayList numbers, ArrayList sublist, int n,
int i) {
if (sublist.sum() == n) {
System.out.println(sublist.toString());
}
else {
for (int j = 0; j < numbers.size(); j++) {
sublist.add(numbers.get(i));
printSublists(numbers, sublist, n, i + 1);
sublist.remove(numbers.get(i));
}
}
}
Of course I already have the method sum()
. The method does this now:
Lets say numbers = [1, 3 , 4]
and n == 4
, then the method should print [4]
and [1 ,3]
, but it only prints [1, 3]
? I think the for-loop has to do the trick right? I would appreciate it if someone puts me on the right track.
update: the values I'm giving to the method:
numbers = [1, 3, 4]
n = 4
i = 0
sublist = []
UPDATE 2:
I forgot to say that I want it to be recursive :)