1 回答

TA貢獻1775條經驗 獲得超11個贊
理解這樣的遞歸情況的典型方法是假設它適用于較小的情況,然后看看較大的情況如何進行。
因此,讓我們假設combinations(['b', 'c', 'd'], 1)
產生值['b']
、then ['c']
、then '[d]'
,同樣combinations(['c', 'd'], 1)
產生['c']
then ['d']
,然后combinations(['d'], 1)
產生 just ['d']
,最后combinations([], 1)
什么也不產生。
現在讓我們來看看combinations(['a', 'b', 'c', 'd'], 2)
:
我們迭代i
from0
到3
:
當
i
=0
,elements[i]
='a'
時,我們看到length
是2
,所以不是== 1
。我們計算remaining = combinations(['b', 'c', 'd'], 1)
,根據我們的假設,得出['b']
then 。因此,對于其中的每一個,我們都會屈服,這意味著我們屈服,然后['c']
['d']
[elements[i], ...(the yielded value)]
['a', 'b']
['a', 'c']
['a', 'd']
當
i
=1
,elements[i]
='b'
時,我們看到 是length
,2
所以不是== 1
。然后我們計算remaining = combinations(['c', 'd'], 1)
,根據我們的假設,得出。因此,對于其中的每一個,我們都會產生,這意味著我們會產生,然后。['c']
['d']
[elements[i], ...(the yielded value)]
['b', 'c']
['b', 'd']
當
i
=2
,elements[i]
='c'
時,我們看到length
是2
,所以不是== 1
。我們計算出remaining = combinations(['d'], 1)
根據我們的假設得出的結果['d']
。因此,對于其中(唯一的)一個,我們產生 ,這[elements[i], ...(the yielded value)]
意味著我們產生['c', 'd']
。當
i
=時3
,elements[i]
='d'
我們看到是length
,2
所以不是== 1
。我們計算“剩余=組合([],1),根據我們的假設,它不會產生任何結果,因此在這種情況下我們也不會產生任何結果。
因此,總的來說,我們得到了以下值:['a', 'b']
、['a', 'c']
、['a', 'd']
、['b', 'c']
、['b', 'd']
和['c', 'd']
,這正是 中兩個元素的組合集合['a', 'b', 'c', 'd']
。
length
當然,您還需要在=時檢查基本情況1
,但這應該很容易做到。
非發電機方法
有時,生成器方法會使代碼更加簡潔且易于理解。然而,這并不是真正的那個時代。
基本上,生成器允許您不必進行復雜的結果收集,而是yield
隨心所欲地收集結果。如果您可以輕松地收集結果,那么非生成器代碼通常會更簡單。這是不使用生成器的相同算法:
const combinations = (elements, length) =>
elements .flatMap ((el, i) =>
length == 1
? [el]
: combinations (elements .slice (i + 1), length - 1)
.map (combo => [el, ...combo])
)
console .log (combinations (['a', 'b', 'c', 'd'], 2))
.as-console-wrapper {max-height: 100% !important; top: 0}
添加回答
舉報