C ++程序生成给定数字列表的所有可能组合
这是一个C++程序,用于生成给定数字列表的所有可能组合
演算法
Begin Take the number of elements and the elements as input. function Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) : If currLen>reqLen then Return Else if currLen=reqLen then Then print the new generated sequence. If s=l then Then return no further element is left. For every index there are two option: either proceed with a start as ‘true’ and recursively call Combi() with incremented value of ‘currLen’ and ‘s’. Or proceed with a start as ‘false’ and recursively call Combi() with only incremented value of ‘s’. End
示例
#include<iostream> using namespace std; void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) // print the all possible combination of given array set { if(currLen > reqLen) return; else if (currLen == reqLen) { cout<<"\t"; for (int i = 0; i < l; i++) { if (check[i] == true) { cout<<a[i]<<" "; } } cout<<"\n"; return; } if (s == l) { return; } check[s] = true; Combi(a, reqLen, s + 1, currLen + 1, check, l); //recursively call Combi() with incremented value of ‘currLen’ and ‘s’. check[s] = false; Combi(a, reqLen, s + 1, currLen, check, l); // recursively call Combi() with only incremented value of ‘s’. } int main() { int i,n; bool check[n]; cout<<"Enter the number of element array have: "; cin>>n; char a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; check[i] = false; } for(i = 1; i <= n; i++) { cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n"; Combi(a, i, 0, 0, check, n); } return 0; }
输出结果
Enter the number of element array have: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 The all possible combination of length 1 for the given array set: 4 3 2 1 The all possible combination of length 2 for the given array set: 4 3 4 2 4 1 3 2 3 1 2 1 The all possible combination of length 3 for the given array set: 4 3 2 4 3 1 4 2 1 3 2 1 The all possible combination of length 4 for the given array set: 4 3 2 1