经典面试题:
a)求一个全排列函数:如p([1,2,3]) ,输出: [123],[132],[213],[231],[321],[323]。
b)求一个组合函数: 如p([1,2,3]) ,输出:[1],[2],[3],[1,2],[2,3],[1,3],[1,2,3]。
对于组合和排列问题拿递归做是很方便的,下面给出代码:
#include <cstdlib>
#include <string.h>
#include <iostream>
#include <stdio.h>
using namespace std;
void theWholeArray(int arr[], int n, int index, string p)
{
char buff[16];
int tmp;
if(index == n)
{
cout<<p<<endl;
return;
}
for(int i = 0; i < n; i++)
{
if(arr[i] != -1)
{
sprintf(buff, "%d", arr[i]);
tmp = arr[i];
arr[i] = -1;
theWholeArray(arr, n, index + 1, p + buff);
arr[i] = tmp;
}
}
}
void theComArray(int arr[], int n, int index, string p)
{
char buff[16];
if(index == n)
{
if(p != "")
cout<<p<<endl;
return;
}
sprintf(buff, "%d", arr[index]);
theComArray(arr, n, index + 1, p + buff);
theComArray(arr, n, index + 1, p + "");
}
int main()
{
int arr[] = {1,2,3};
theWholeArray(arr, 3, 0, "");
return 0;
}