The main problem is that you always return sum != n When the amount becomes greater than n , you never stop, therefore, StackOverflowError This means that we need to add a check and complete when the amount becomes larger:
public static void test_2(String path, int sum, int n) { if (sum == n) { System.out.println(path); } else if (sum < n) {
As a side note in your last two calls, you wrote 1 and 2 instead of 3 and 4, but that was probably just a typo.
The output of the call test_2("", 0, 4) :
1 1 1 1 1 1 2 1 2 1 1 3 2 1 1 2 2 3 1 4
But note that your current code is not very dynamic: it will not work if you give values ββgreater than 4 for n . I would suggest a bit of refactoring.
source share