问题描述:
给定值n,求解出1到n的所有数字组合排序
采用递归思路,代码如下:
#include<iostream>
#include <assert.h>
using namespace std;
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
return ;
}
void permutation(int *p, int base, int len)
{
int i;
if(base == len - 1)
{
for(i = 0; i < len; i++)
{
cout << p[i] << ((i == len - 1)?'\n':',');
}
}
for(i = base; i < len; i++)
{
swap(p+base, p+i);
permutation(p, base+1, len);
swap(p+base, p+i);
}
return;
}
int main()
{
int *p;
int n;
cout << "please input the number: " << endl;
cin >> n;
assert(n >= 0);
p = new int[n];
int i;
for(i=0; i < n; i++)
{
p[i] = i + 1;
}
permutation(p, 0, n);
delete p;
return 0;
}