【问题标题】:I'm trying to understand how to print all the possible combinations of a array我试图了解如何打印数组的所有可能组合
【发布时间】:2020-01-05 15:30:25
【问题描述】:
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.

【问题讨论】:

  • 我不确定你是想理解这个(不完整的)sn-p 还是解决问题。如果是后者:stackoverflow.com/questions/104420/…
  • 我正在尝试理解这个sn-p,完整的代码在链接中提供。

标签: python algorithm recursion combinations backtracking


【解决方案1】:

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

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 &lt; values_left_to_print)

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

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 1970-01-01
    • 2022-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多