此递归函数如何工作?

时间:2019-10-18 16:18:17

标签: c++ algorithm recursion

我一直在寻找最小和分区问题的解决方案,而我发现了这个Link

我找不到递归在此函数中的工作原理,尤其是基本条件。

例如,我有一个更笼统的问题,用于计算inc递归,直到n将为-1,然后将其转到基本情况,然后为case 2

您可以在下面看到功能主体。

// Partition the set S into two subsets S1, S2 such that the
// difference between the sum of elements in S1 and the sum
// of elements in S2 is minimized
int minPartition(int S[], int n, int S1, int S2)
{
    // base case: if list becomes empty, return the absolute
    // difference between two sets
    if (n < 0)
    {
        return abs(S1 - S2);

    }

    // Case 1. include current item in the subset S1 and recur
    // for remaining items (n - 1)
    int inc = minPartition(S, n - 1, S1 + S[n], S2);

    // Case 2. exclude current item from subset S1 and recur for
    // remaining items (n - 1)
    int exc = minPartition(S, n - 1, S1, S2 + S[n]);
    return min (inc, exc);

}

我试图以适合标准的适当方式介绍我的问题,但请告知我是否可以做得更好,并对社区产生更积极的影响。

非常感谢您的时间和事先的帮助。

1 个答案:

答案 0 :(得分:0)

首次调用minPartition()时,它将一直运行到最终到达inc并在其中运行minPartition()的调用,并且在该迭代中调用,要么遍历基本案例,要么遍历案例1,它会一直这样做直到基础案例发生。发生这种情况时,它将返回调用,然后exc将运行其minPartition()的调用,并基本上重复inc发生的处理,并在到达基本情况时将其重复返回到inc的另一个先前迭代,重复直到回到inc的第一次迭代,然后exc将运行,exc完成后,{{1} }函数只是从min()inc中的值中找出最小的差异。

希望有帮助!