Code:
//For example, if N=4 return {{1,1,1,1},{1,1,2},{1,3}}
//if N = 6 ... expected results
//1,1,1,1,1,1
//2,1,1,1,1
//2,2,1,1
//2,2,2
//3,1,1,1
//3,2,1
//3,3
//4,1,1
//4,2
//5,1
import java.util.*;
class Solution {
public static void addNext(ArrayList
if (sum == target) {
results.add(list);
return;
}
while (sum + last > target) {
last--;
}
int less = last - 1;
if ( !isFirst && less > 0 && less + last < target ) {
ArrayList
addNext(results, copyList, sum, less, target, false);
}
sum = sum + last;
list.add(last);
addNext(results, list, sum, last, target, false);
}
public static void main(String[] args) {
int n = 6;
ArrayList
ArrayList
for (int i=1; i
list = new ArrayList
addNext(results, list, 0, i, n, true);
}
print(results);
}
public static void print(ArrayList
for (ArrayList
for (Integer i: list) {
System.out.print(String.format("%d ", i));
}
System.out.println("\n----------");
}
}
}
Output:
Execute and get the output
More Java Programs: