我正在尝试编写一个算法来获取M个元素的多维数组中N个元素的所有可能组合.
就像是:
function getCombinations(arr, n){
...
}
var arr = [ ["A"],["B","C"],["D","E"]];
var n = 2;
getCombinations(arr,n);
这应该产生:
[
["A","B"],["A","C"],["A","D"],["A","E"],
["B","D"],["B","E"],
["C","D"],["C","E"]
]
数组内部的元素数量可能会有所不同,唯一设置的是元素的组合数量.
顺序没关系,但你不能重复,我的意思是[“A”,“B”] == [“B”,“A”],所以第二个没有考虑.
有帮助吗?
解决方法:
ChrisB解决方案有一个错误,他没有在arr.shift之前缓存循环的长度,并且它没有返回最后一个组合,我认为这将完成这项工作:
function getCombinations (arr, n) {
var i, j, k, elem, l = arr.length, childperm, ret = [];
if (n == 1){
for (i = 0; i < arr.length; i++) {
for (j = 0; j < arr[i].length; j++) {
ret.push([arr[i][j]]);
}
}
return ret;
}
else {
for (i = 0; i < l; i++) {
elem = arr.shift();
for (j = 0; j < elem.length; j++) {
childperm = getCombinations(arr.slice(), n-1);
for (k = 0; k < childperm.length; k++) {
ret.push([elem[j]].concat(childperm[k]));
}
}
}
return ret;
}
}
getCombinations([["A"],["B"],["C","D"]], 2);
// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"]]
getCombinations([["A"],["B"],["C"],["D"]], 2);
// [["A", "B"], ["A", "C"], ["A", "D"], ["B", "C"], ["B", "D"], ["C", "D"]]