讓我們試一下:
Knuths
1. Find the largest index j such that a[j] < a[j + 1]. If no
such index exists, the permutation is the last permutation.
{20,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
> > = = = = = = = = = = = = = = = = =
哎呀,沒有索引j
這樣a[j] < a[j + 1]
。但是,因爲我們希望所有不同的排列組合,我們可以在每個陣列和保障,我們從頭開始進行排序:
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,20}
1. Find the largest index j such that a[j] < a[j + 1]. If no
such index exists, the permutation is the last permutation.
j = 18 since a[18] < a[19]
2. Find the largest index l such that a[j] < a[l]. Since j + 1
is such an index, l is well defined and satisfies j < l.
l = 19 since a[18] < a[19]
3. Swap a[j] with a[l].
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,10}
4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,10}
讓我們做幾個:
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,10}
yields {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,0,20}
yields {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,20,0}
yields {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,0,10}
yields {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,20,10,0}
yields {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,0,0,20}
...
正如你所看到的,大元素正在穩定(明顯地)向左移動,直到:
{10,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
yields {20,10,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
並且沒有重複的排列結束。
我很困惑。鏈接線程中的代碼正在執行一個詞典增量,對於具有重複元素的多重集合,它實際上工作正常,不需要HashSet。 –
嗯,我會說,所有你需要做的是應用算法之前使用的輸入的不同的子集。 –
@DavidEisenstat它可以正常工作,但計算需要很長時間。如果我不使用HashSet,我會得到2.4 * 10^18的結果。 – jacobz