我有来自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);
}
}
当它调用printPartitions(4, 4, "");
时,它会给出以下输出:
1 1 1 1
1 1 2
2 2
1 3
4
如何在这样的数组中获取输出:
[[1,1,1,1],[1,1,2],[2,2],[1,3],[4]]
答案 0 :(得分:0)
在这种情况下,您应该将值收集到数组中。为了简化“添加”操作,我用一个列表替换了数组(对于一个你应该维护索引的数组):
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);
}
输出:
[[1, 1, 1, 1], [1, 1, 2], [2, 2], [1, 3], [4]]