【发布时间】:2018-01-03 00:21:42
【问题描述】:
给定一个具有 n 个键的数组或对象,我需要找到长度为 x 的所有组合。
鉴于X 是可变的。 binomial_coefficient(n,x).
目前我正在使用这个:
function combine(items) {
var result = [];
var f = function(prefix, items) {
for (var i = 0; i < items.length; i++) {
result.push(prefix + items[i]);
f(prefix + items[i], items.slice(i + 1));
}
}
f('', items);
return result;
}
var combinations = combine(["a", "b", "c", "d"]);
输出是:
["a", "ab", "abc", "abcd", "abd", "ac", "acd", "ad", "b", "bc", "bcd", "bd", "c", "cd", "d"]
所以如果我想要来自n=4 的二项式系数x=3,我会选择所有长度等于3 的字符串。 {abc, abd, acd, bcd}。
所以我分两步完成。
有没有更高效、复杂度更小的算法?
【问题讨论】:
-
谢谢大家。我创建了一个 jsperf 测试,其中包含所有答案 here,在不同浏览器和 PC 中测试了几个值之后,我认为 David 有最快的解决方案
标签: javascript algorithm dynamic-programming memoization binomial-coefficients