[英]Get all (number of) combinations of an array
從昨天開始,我一直在努力做到這一點,盡管還沒有運氣。 我找到了解決方案,在我想要完成的事情上總是有細微的差別。
我試圖獲得所有可能的組合,稍微像這樣: combination_k ,但我也希望相同的項目與自身配對,所以給出以下內容:
輸入[1, 4, 5]
和2
(組合數)應返回:
[1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]
輸入[1, 4, 5]
和3
應該返回:
[1, 1, 1], [1, 1, 4], [1, 1, 5], [1, 4, 4], [1, 4, 5], [4, 4, 4], [4, 4, 5], [5, 5, 5], [5, 5, 4], [5, 5, 1]
(順序不重要)。
我一直在調整combination_k,它讓我足夠遠,它可以與2一起使用,但是當我提供3作為參數時它不起作用。
const combinations = getAllCombinations([1, 4, 5], 2);
// combinations = [1, 1], [1, 4], [1, 5], [4, 4], [4, 5], [5, 5]
歡迎任何提示!
該問題通常被稱為具有重復的 k 組合。
這是一個依賴遞歸來獲得所需結果的解決方案:
const combinations = (array, r) => { const result = []; const fn = (array, selected, c, r, start, end) => { if (c == r) { result.push([...selected]); return; } for (let i = start; i <= end; i++) { selected[c] = array[i]; fn(array, selected, c + 1, r, i, end); } } fn(array, [], 0, r, 0, array.length - 1); return result; } console.log(combinations([1, 4, 5], 3));
您提供的代碼的修改版本:
function getAllCombinations(arr, n) { if (n <= 0) return []; if (n === 1) return [...arr]; return arr.reduce((acc, cur, i) => { const head = arr.slice(i, i + 1); const combinations = getAllCombinations(arr.slice(i), n - 1).map(x => head.concat(x)); return [...acc, ...combinations]; }, []); } console.log(getAllCombinations([1, 4, 5], 2).join('|')); console.log(getAllCombinations([1, 4, 5], 3).join('|'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.