javascript - 获取数组的所有(数量)组合
问题描述
从昨天开始,我一直在努力做到这一点,尽管还没有运气。我找到了解决方案,在我想要完成的事情上总是有细微的差别。
我试图获得所有可能的组合,稍微像这样: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));
推荐阅读
- flutter - 如何在 Flutter App 中拥有一个全局单例对象
- r - 用 R 抓取 HTML 表格
- websocket - 如何使用机器人框架从 Websocket Connection 发送和接收响应
- javascript - 在 Spring Boot 中无法获取 cookie 值
- chef-infra - 厨师中的 ruby Mixlib::ShellOut 解析问题
- c# - 等待另一个任务 C# 更新对象
- html - 以更好的方式处理按钮的活动选择
- java - 如何限制JVM内存消耗?
- python - 如何向现有的 pandas 数据框添加新列
- python - 如何对文本文件进行数字排序?