假设我有以下数组:
A = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h'],
['i'],
['j', 'k', 'l']
]
我想找到每个数组的元素与其他数组的元素的所有可能组合(即“adgij”是一种可能性,而不是“abcde”)。
我可以强制它,然后像这样循环所有内容(javascript):
var A = [
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h'],
['i'],
['j', 'k', 'l']
],
combinations,
newCombinations = [];
A.forEach(function(a, index) {
newCombinations = [];
if (index === 0) {
newCombinations = a;
} else {
a.forEach(function(val){
combinations.forEach(function(combination){
newCombinations.push(combination + val);
});
});
}
combinations = newCombinations;
});
这个方法的问题是它是广度优先的,所以如果我想在n次迭代后停止,我会有不完整的组合。
有没有办法用深度优先法得到所有可能的组合?
最佳答案
伪代码中的一个简单递归函数。
每个递归步骤从当前索引的数组中选择一个元素,并为下一个索引调用函数。current
可以只是一个列表。
printAllCombinations(A, {}, 0)
printAllCombinations(A, current, index)
if index == A.length
print current
return
for each element e in A[index]
current.addToBack(e)
printAllCombinations(A, current, index + 1)
current.removeLast(e)
关于algorithm - 深度优先组合算法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20984495/