www说
通过这个问题的小调整,我希望我的解决方案更有效,因为它使用位运算符来生成所有子集。var sets = (function(input, size) {
var results = [], result, mask, i, total = Math.pow(2, input.length);
for (mask = size; mask < total; mask++) {
result = [];
i = input.length - 1;
do {
if ((mask & (1 << i)) !== 0) {
result.push(input[i]);
}
} while (i--);
if (result.length >= size) {
results.push(result);
}
}
return results; })(['a','b','c','d','e','f'], 2);console.log(sets);
饮歌长啸
以下是使用ECMAScript 2015 生成器函数查找所有组合的方法:function* generateCombinations(arr) {
function* doGenerateCombinations(offset, combo) {
yield combo;
for (let i = offset; i < arr.length; i++) {
yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
}
}
yield* doGenerateCombinations(0, []);}for (let combo of generateCombinations([1, 2, 3, 4, 5])) {
console.log(JSON.stringify(combo));}要限制问题中要求的最小尺寸,只需确保组合的长度,然后再产生它:function* generateCombinations(arr, minSize) {
function* doGenerateCombinations(offset, combo) {
if (combo.length >= minSize) {
yield combo;
}
for (let i = offset; i < arr.length; i++) {
yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
}
}
yield* doGenerateCombinations(0, []);}for (let combo of generateCombinations([1, 2, 3, 4, 5], 2)) {
console.log(JSON.stringify(combo));}限制点yield允许以可读方式使该功能适应其他常见用例,例如,选择精确大小的所有组合:function* generateCombinations(arr, size) {
function* doGenerateCombinations(offset, combo) {
if (combo.length == size) {
yield combo;
} else {
for (let i = offset; i < arr.length; i++) {
yield* doGenerateCombinations(i + 1, combo.concat(arr[i]));
}
}
}
yield* doGenerateCombinations(0, []);}for (let combo of generateCombinations([1, 2, 3, 4, 5], 2)) {
console.log(JSON.stringify(combo));}