2024-04-25 23:20:32 发布
网友
考虑一下有三个数组的情况:
X = {A , B , C}; Y = {D , E , F}; Z = {G , H , I};
C1 = {A , D , G}; C2 = {A , D , H}; ... C4 = {A, E , G}; ... C10 = {B , D , G}; ... ...
“combination”函数递归地寻找答案。把所有元素放在一个叫做“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); }
您可以使用STL内的算法头,使用下一个置换函数您可以生成所有可能的组合。注意:它只会生成一个置换,您必须在循环中使用它。您可以在这个链接上看到函数的文档。Generating Permutation
试试这个
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))
如果您事先不知道存在多少个iterable,那么可以在程序运行时将它们添加到列表中,然后运行product(*args),例如
product(*args)
items = [x, y] items.append(z) for a in product(*items): print(a)
“combination”函数递归地寻找答案。把所有元素放在一个叫做“arr”的数组中,我认为这个数组的大小是6。下面是一个使用haw函数的示例:
您可以使用STL内的算法头,使用下一个置换函数您可以生成所有可能的组合。注意:它只会生成一个置换,您必须在循环中使用它。您可以在这个链接上看到函数的文档。Generating Permutation
试试这个
如果您想更实际一些,可以通过嵌套循环来获得多个集合中的所有组合。在python中,是这样的
如果您事先不知道存在多少个iterable,那么可以在程序运行时将它们添加到列表中,然后运行
product(*args)
,例如相关问题 更多 >
编程相关推荐