递归函数,返回结果为数组

时间:2013-11-26 04:27:09

标签: java

如何更改此功能以使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"} }

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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[]>可能会更好。