1、给一个字符串,输出它的全排列
思想:递归,先考虑第一个位置能出现的所有字符,然后递归考虑第二个位置能出现的字符.................................
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
void permutation(char* pstr,char* pbegin)
{
if(*pbegin == '\0') printf("%s\n",pstr);
else{
for(char* pch = pbegin; *pch != '\0'; pch++)
{
char temp = *pch;
*pch = *pbegin;
*pbegin = temp;
permutation(pstr,pbegin+1);
temp = *pch;
*pch = *pbegin;
*pbegin = temp;
}
}
}
int main()
{
char a[100];
scanf("%s",a);
permutation(a,a);
return 0;
}
用模板来实现
#include<iostream>
#include<string.h>
using namespace std;
template<class T>
void permutation(T* a,int cur,int n)
{
if(cur == n)
{
for(int i = 0; i < n; i++) cout<<a[i]<<" ";
cout<<endl;
}
else{
for(int i = cur; i < n; i++)
{
T temp = a[i];
a[i] = a[cur];
a[cur] = temp;
permutation(a,cur+1,n);
temp = a[i];
a[i] = a[cur];
a[cur] = temp;
}
}
}
int main()
{
int n;
cin>>n;
int a[100];
for(int i = 0; i < n; i++) cin>>a[i];
permutation(a,0,n);
return 0;
}
2、从n个数中选m个,输出它的所有组合
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N = 1000;
int a[N];//choose m numbers from 1 to n, k means the max number in the combination,num means num numbers
void combination(int num,int k,const int &n,const int &m)
{
if(num == m) {
for(int i = 0; i < m; i++)
cout<<a[i]<<" ";
cout<<endl;
return;
}
for(int i = k+1; i <= n; i++)
{
a[num] = i;
combination(num+1,i,n,m);
}
}
int main()
{
int n,m;
cin>>n>>m;
combination(0,0,n,m);
return 0;
}
3、输出1-n的所有组合
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
const int N = 1000;
int a[N];
void combination(int num,int k,const int &n)
{
for(int i = 0; i < num; i++)
cout<<a[i]<<" ";
cout<<endl;
if(num == n) return;
for(int i = k+1; i <= n; i++)
{
a[num] = i;
combination(num+1,i,n);
}
}
int main()
{
int n;
cin>>n;
combination(0,0,n);
return 0;
}