[英]I'm trying to understand how to print all the possible combinations of a array
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 的邊緣情況是什么。
嘗試將變量分組為更容易理解的部分,例如
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,但序列中的值永遠只在指數增加從左向右給定數組中,這樣的組合將結束,因為
i
將到達end
的存在之前,能夠找到3個值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.