gpt4 book ai didi

java - 递归函数,以数组形式返回结果

转载 作者:太空宇宙 更新时间:2023-11-04 15:23:04 26 4
gpt4 key购买 nike

如何更改此函数以将 String[][] 作为返回类型并返回可能组合的数组,而不是仅打印出找到的组合?

static void combinations2(String[] arr, int len, int startPosition, String[] result){
if (len == 0){
System.out.println(Arrays.toString(result));
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations2(arr, len-1, i+1, result);
}
}

示例:

combinations2({ "Value1", "Value2", "Value3" }, 2, 0);

应该返回

{ { "Value1", "Value2" }, {"Value1", "Value3"}, {"Value2", "Value3"} }

最佳答案

你可以这样做:

static void combinations2(String[] arr, int len, int startPosition, String[] result, String[][] allResults){
if (len == 0){
//Add result to allResults here
return;
}
for (int i = startPosition; i <= arr.length-len; i++){
result[result.length - len] = arr[i];
combinations2(arr, len-1, i+1, result);
}
}

foo() {
String[][] allResults = new String[][];
combinations2(...);
//allResults now holds all the String[].
//No return statement necessary since arrays, like all Java objects, are passed as references.
}

但你可能会更好地使用 allResults作为ArrayList<String[]> .

关于java - 递归函数,以数组形式返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20208495/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com