2013-11-26 2 views
1

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

메소드에서 반환 할 수있는'String [] []'이 없습니다. – SudoRahul

+0

먼저, 반환 유형을 변경해야합니다. 둘째, 반환 된 배열에 무엇을 넣으려고합니까? – Andrew

+0

발견 된 조합은 어디에 인쇄됩니까? – Ashish

답변

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. 
} 

그러나 당신은 ArrayList<String[]>allResults와 떨어져 아마 더 좋을 것 같아.

+0

어떻게 각 결과를 allResults 배열에 추가합니까? 나는 당신의 모범에서 빠진 것이 있다고 생각합니다. – Zulakis

+1

* 배열은 참조로 전달되므로 * Java는 순전히 ** 패스 바이 값입니다 **. 그 진술을 검열하거나 수정할 수도 있습니다. – SudoRahul

+0

@ R.J : 사실, 나는 그것을 바꿔 썼다. 그 구별은 항상 나를 잡는다. –