写这篇博文的原因是源于今年校招笔试常考的一道题。鉴于我是一个特别懒的人,但是由于多次跪在这道题上,我觉得我不得不或者说应当在这道题上做一些事情了。
题目原意是要输出一个字符串的全排列。(各个公司可能会有题目的不同版本)
输入:bcd
输出:bcd bdc cbd cdb dcb dbc
代码如下:
#include <iostream>
using namespace std;
char *str;//存储需要输出全排列的char数组
char * buffer;//用于输出的缓存
int *count1; //用于记录已输出位置的辅助数组
int n ;
void print1(int i);
void print1(int i)//声明后立刻定义,其实可以直接把声明去掉的,但是我忍了:-D
{
if(i==n)
{
for(int j = 0 ; j < n ; j++)
{
cout<<buffer[j];
}
puts("");
}
for(int k = 0 ; k < n ;k++)
{
if(count1[k] > 0)
{
--count1[k];
buffer[i] = str[k];
print1(i+1);
count1[k]++;
}
}
}
int main(){
cin >>n;
str = new char[n];
buffer = new char [n];
count1 = new int [n];
for(int i = 0 ; i < n; i ++)
{
cin>>str[i];
count1[i]=1;
}
print1(0);
return 0;
}
using namespace std;
char *str;//存储需要输出全排列的char数组
char * buffer;//用于输出的缓存
int *count1; //用于记录已输出位置的辅助数组
int n ;
void print1(int i);
void print1(int i)//声明后立刻定义,其实可以直接把声明去掉的,但是我忍了:-D
{
if(i==n)
{
for(int j = 0 ; j < n ; j++)
{
cout<<buffer[j];
}
puts("");
}
for(int k = 0 ; k < n ;k++)
{
if(count1[k] > 0)
{
--count1[k];
buffer[i] = str[k];
print1(i+1);
count1[k]++;
}
}
}
int main(){
cin >>n;
str = new char[n];
buffer = new char [n];
count1 = new int [n];
for(int i = 0 ; i < n; i ++)
{
cin>>str[i];
count1[i]=1;
}
print1(0);
return 0;
}
其实还是建议把代码具体读一下,如果实在不想读,思路如下:
题目意思是要我们实现一个N!的时间复杂度。我们可以考虑模拟一个n^n的然后再通过条件判断降为n!的。递归过程主要就是做的这么一回事。
好吧,我还是有点懒。还是看代码吧。