这个优雅的解决方案怎么样?扩展生成 nCr 的代码以迭代 r=1 直到 n!
#include<iostream>
using namespace std;
void printArray(int arr[],int s,int n)
{
cout<<endl;
for(int i=s ; i<=n-1 ; i++)
cout<<arr[i]<<" ";
}
void combinateUtil(int arr[],int n,int i,int temp[],int r,int index)
{
// What if n=5 and r=5, then we have to just print it and "return"!
// Thus, have this base case first!
if(index==r)
{
printArray(temp,0,r);
return;
}
// If i exceeds n, then there is no poin in recurring! Thus, return
if(i>=n)
return;
temp[index]=arr[i];
combinateUtil(arr,n,i+1,temp,r,index+1);
combinateUtil(arr,n,i+1,temp,r,index);
}
void printCombinations(int arr[],int n)
{
for(int r=1 ; r<=n ; r++)
{
int *temp = new int[r];
combinateUtil(arr,n,0,temp,r,0);
}
}
int main()
{
int arr[] = {1,2,3,4,5};
int n = sizeof(arr)/sizeof(arr[0]);
printCombinations(arr,n);
cin.get();
cin.get();
return 0;
}
输出:
1
2
3
4
5
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
1 2 3 4
1 2 3 5
1 2 4 5
1 3 4 5
2 3 4 5
1 2 3 4 5