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 🙂
Recursion stops when you see the first sublist with a sum of
n. The problem is not (only) the loop but the exit criteria.Your recursive function should stop when the sublist length is 0.Here I just wrote a working, recursive solution for your problem. It is different but I wasn’t able to fix yours. While you start with an empty sublist, I chose to init the recursion with the full list an divide it into smaller sublists. This creates a tree like structure:
We see immediately, that we have to walk down “right” until we reach the first leaf (
1), then we only walk “left”. This way we visit all sublists only once.Here’s the idea written in Java:
And that’s the output: