[英]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.