考虑具有三个数组的情况:
X = {A , B , C};
Y = {D , E , F};
Z = {G , H , I};
如何从这三个数组(C ++或Python)生成所有可能的组合,就像
C1 = {A , D , G};
C2 = {A , D , H};
...
C4 = {A, E , G};
...
C10 = {B , D , G};
...
...
答案 0 :(得分:2)
试试这个
from itertools import product
x = {'a', 'b', 'c'}
y = {'d', 'e', 'f'}
z = {'g', 'h', 'i'}
for a in product(x, y, z):
print(a)
如果你想更加脚踏实地,可以通过嵌套循环完成从多个集合中获取所有组合。在python中,它就像这样
for e1 in x:
for e2 in y:
for e3 in z:
print((e1, e2, e3))
如果你不知道预先存在多少个可迭代物,你可以在程序运行时继续将它们附加到列表中,然后运行product(*args)
,例如
items = [x, y]
items.append(z)
for a in product(*items):
print(a)
答案 1 :(得分:0)
您可以在STL中使用Algorithm标头,使用next_permutation函数可以生成所有可能的组合。注意:它只会产生一个排列,你必须在循环中使用它。您可以在此链接上查看该功能的文档。Generating Permutation
答案 2 :(得分:0)
“组合”功能递归工作以找到答案。只需将所有元素放在一个名为“arr”的数组中,我认为它的大小为6.以下是使用该函数的haw的示例:
#include <iostream>
#include <vector>
using namespace std;
void combinations(string arr[], int len, int startPosition, string result[]){
if (len == 0){
cout <<"{";
for (int i = 0; i < 2; i++) {
cout << result[i] <<", ";
}
cout << result[2]+ "}" << endl;
return;
}
for (int i = startPosition; i <= 6-len; i++){
result[3 - len] = arr[i];
combinations(arr, len-1, i+1, result);
}
}
int main(int argc, const char * argv[]) {
string arr[] = {"A","B","C","D","E","F"};
string temp[3];
combinations(arr, 3, 0, temp);
}