递归函数中的多项选择

时间:2018-12-13 17:59:08

标签: recursion math combinatorics

因此,我们有一项任务是打印给定大小为n的数组中r个元素的所有可能组合。例如,如果输入数组为{1、2、3、4}且r为2,则输出应为{ 1,2},{1,3},{1,4},{2,3},{2,4}和{3,4}。 (来自here

所以在调试模式下,我注意到了这一点。我不知道是什么魔术使它跳到了递归标记(标记为“ HERE 1”),而另一些时间跳到了其他标记(“ HERE 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 :(得分:0)

没有魔术-函数进行第一个递归调用,返回后进行第二个递归调用-就像通常的函数A依次调用函数B和函数C一样