生成所有可能的子集的 C++ 程序,每个子集中的元素恰好为 k
这是一个C++程序,用于生成所有可能的子集,每个子集中有k个元素。
算法
Begin function PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l): If currLen > reqLen Return Else if currLen = reqLen Then print the new generated sequence. If s = l Then return no further element is left. For every index there are two options: either proceed with a start as ‘true’ and recursively call PossibleSubSet() with incremented value of ‘currLen’ and ‘s’. Or proceed with a start as ‘false’ and recursively call PossibleSubSet() with only incremented value of ‘s’. End
示例
#includeusing namespace std; void PossibleSubSet(char a[], int reqLen, int s, int currLen, bool check[], int l) //打印给定数组集的所有可能组合 { if(currLen > reqLen) return; else if (currLen == reqLen) { cout<<"\t"; for (int i = 0; i < l; i++) { if (check[i] == true) { cout<>n; char a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<>a[i]; check[i] = false; } cout<<"\nEnter the length of the subsets required: "; cin>>m; cout<<"\nThe possible combination of length "< 输出结果 输入元素数量: 7 Enter 1 element: 7 Enter 2 element: 6 Enter 3 element: 5 Enter 4 element: 4 Enter 5 element: 3 Enter 6 element: 2 Enter 7 element: 1 Enter the length of the subsets required: 6 The possible combination of length 6 for the given array set: 7 6 5 4 3 2 7 6 5 4 3 1 7 6 5 4 2 1 7 6 5 3 2 1 7 6 4 3 2 1 7 5 4 3 2 1 6 5 4 3 2 1