实现一个函数,打印出一个字符串中字符的所有可能顺序。换言之,就是打印出原来字符串中所有字符的全排列。例如,对于字符串“hat”,函数应该打印出字符串“tha”,“aht”,“tah”,“ath”,“hta”,“hat”。将输入字符串中的每个字符作为一个独立的字符,即使它们发生重复。对于字符串“aaa”,函数应该打印出6个“aaa”。可以按任何顺序打印出全排列。
程序的代码如下:
#include "stdafx.h"
#include <iostream.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
void DoPermute(char in[], char out[], int used[], int length, int recurslev)
{
int i;
// Base case
if(recurslev == length)
{
printf("%s/n", out); // Print permutation
return;
}
// Recursive case
for(i = 0; i < length; i++)
{
if(used[i]) // if used, skip to next letter
continue;
out[recurslev] = in[i]; // Put current letter in output
used[i] = 1;
DoPermute(in, out, used, length, recurslev + 1);
used[i] = 0;
}
}
int Permute(char inString[])
{
int length, i, *used;
char *out;
length = strlen(inString);
out = (char*)malloc(length + 1);
if(!out) // Failed
return 0;
// So printf doesn't run past the end of the buffer
out[length] = '/0';
used = (int*)malloc(sizeof(int) * length);
if(!used) // Failed
return 0;
// Start with no letters used, so zero array
for(i = 0; i < length; i++)
{
used[i] = 0;
}
DoPermute(inString, out, used, length, 0);
free(out);
free(used);
return 1; // Success
}
int main()
{
char str[] = "hat";
Permute(str);
return 0;
}
// 程序的执行结果如下: