我有以下代码来自 打印所有给定整数作为输入的唯一整数分区
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]]
在这种情况下,
您应该将值收集到数组中。我用列表替换了数组,以简化"添加"操作(对于数组,您还应该维护索引(:
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]]