我试图了解如何打印数组的所有可能组合

问题描述 投票:0回答:1
i = start; 
while(i <= end and end - i + 1 >= r - index): 
    data[index] = arr[i]; 
    combinationUtil(arr, data, i + 1, 
                    end, index + 1, r); 
    i += 1; 

我很难理解为什么,需要“ end-i + 1> = r-index”这种情况,我尝试运行代码,无论有没有,它都会产生相同的输出,我想知道什么导致这种情况返回False的边缘情况。

The full code is available here.

python algorithm recursion combinations backtracking
1个回答
0
投票

[尝试将变量分组为更容易理解的部分,例如]

int values_left_to_print = r - index; // (size of combination to be printed) - (current index into data)
int values_left_in_array = end - i + 1; // number of values left until the end of given arr

现在我们可以这样解释它:

for (int i = start; i <= end && (values_left_in_array >= values_left_to_print); i++)  
{

因此,如果i在给定数组的end附近,并且剩余的值不足以打印完整组合,则循环(和功能)将停止。让我们看一个例子:

给出

arr = {1,2,3,4}
n = 4; // size of arr
r = 3; // size of combination

[顶层函数将开始与1形成组合,然后与2形成(1,2,3),(1,2,4),(1,3,4)]

它不会尝试3和4,因为(values_left_in_array < values_left_to_print)

如果条件不存在,则该函数将尝试3和4,但是序列中的值只会在给定数组中从左到右从索引开始增加,因此组合将结束,因为我将到达结束却找不到3个值。

© www.soinside.com 2019 - 2024. All rights reserved.