簡體   English   中英

遞歸函數,以數組形式返回結果

[英]Recursive function, return results as array

如何更改此函數以將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[]>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM