I have the following code from Print all unique integer partitions given an integer as input
void printPartitions(int target, int maxValue, String suffix) {
if (target == 0)
System.out.println(suffix);
else {
if (maxValue > 1)
printPartitions(target, maxValue-1, suffix);
if (maxValue <= target)
printPartitions(target-maxValue, maxValue, maxValue + " " + suffix);
}
}
When it calls printPartitions(4, 4, "");
it gives the below output:
1 1 1 1
1 1 2
2 2
1 3
4
How can I get the output in an array like this:
[[1,1,1,1],[1,1,2],[2,2],[1,3],[4]]
f-CJ
4,5412 gold badges33 silver badges29 bronze badges
asked May 28, 2017 at 12:55
1 Answer 1
You should collect your values to an array in this case. I've replaced the array with a list, for simplification of "add" operation (for an array you should maintain also indexes):
void printPartitions(int target, int maxValue, List<String> suffix, List<List<String>> list) {
if (target == 0) {
list.add(suffix);
} else {
if (maxValue > 1)
printPartitions(target, maxValue-1, suffix, list);
if (maxValue <= target) {
List<String> tmp = new ArrayList<String>();
tmp.add(0, String.valueOf(maxValue));
tmp.addAll(suffix);
printPartitions(target-maxValue, maxValue, tmp, list);
}
}
}
void callPrintPartitions() {
List<List<String>> list = new ArrayList<List<String>>();
printPartitions(4, 4, new ArrayList<String>(), list);
System.out.println(list);
}
Output:
[[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]
answered May 28, 2017 at 15:57
lang-java