Множественный выбор в рекурсивной функции - PullRequest
0 голосов
/ 13 декабря 2018

Таким образом, у нас есть эта задача, чтобы напечатать все возможные комбинации r элементов в данном массиве размера n. Например, если входной массив равен {1, 2, 3, 4} и r равен 2, то результат должен быть {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} и {3, 4}.(С здесь )

Так что в режиме отладки я это заметил.И мне интересно, Какая магия заставляет его переходить к рекурсивной метке (помеченной как «ЗДЕСЬ 1») и в другой раз к другой метке («ЗДЕСЬ 2»), поскольку нет операторов «if» или других операторов ??

 class MainClass {

 static void combinationUtil(int mainArr[], int mainArrSize, int 
 resultLength, int tempArrIndex, int tempArr[], int mainArrIndex){

    // Current combination is ready to be printed, print it
    if (tempArrIndex == resultLength)
    {
        for (int j=0; j<resultLength; j++)
            System.out.print(tempArr[j]+" ");
        System.out.println("");
        return;
    }

    // When no more elements are there to put in data[]
    if (mainArrIndex >= mainArrSize)
        return;

    // current is included, put next at next location
    tempArr[tempArrIndex] = mainArr[mainArrIndex];

 **//HERE 1**
    combinationUtil(mainArr, mainArrSize, resultLength, tempArrIndex+1, 
    tempArr,mainArrIndex+1);

    // current is excluded, replace it with next
 **//HERE 2**
    combinationUtil(mainArr, mainArrSize, resultLength, tempArrIndex, 
    tempArr, mainArrIndex+1);
}

    // Print all combination using temprary array 'data[]'

    static void printCombination(int mainArr[], int mainArrSize, int resultLength)    {
    int data[]=new int[resultLength];

    combinationUtil(mainArr, mainArrSize, resultLength, 0, data, 0);
}

/*Driver function to check for above function*/
public static void main (String[] args) {
    int arr[] = {50, 51, 52, 53, 54};
    int r = 3;
    int n = arr.length;
    printCombination(arr, n, r);
}

}

1 Ответ

0 голосов
/ 13 декабря 2018

Волшебства нет - функция делает первый рекурсивный вызов и после возврата делает второй рекурсивный вызов - так же, как обычная функция A вызывает как функцию B, так и функцию C в порядке

...