输出一个字符串的全排列

来源:互联网 发布:域名注册可靠吗 编辑:程序博客网 时间:2024/05/23 16:42

输出一个字符串的全排列


给出一个字符串S(可能又重复的字符),按照字典序从小到大,输出S包括的字符组成的所有排列。例如:S = "1312",输出为:112311321213123113121321211321312311311231213211Input输入一个字符串S(S的长度 <= 9,且只包括0 - 9的阿拉伯数字)OutPut输出S所包含的字符组成的所有排列

解题思路:
先考虑一个更简单的情况:字符串中没有重复的字符,那么问题就是先对字符串排序,再进行全排列。

可是现在有重复字符,必须要从中剔除重复的。注意到:

对"112"(不考虑重复字符)进行全排列,结果如下:112121112121211211*发现凡是重复的排列,都<=前一个合法的排列*所以只要用一个数组存放前一个合法排列即可。

代码如下:

#include <stdio.h>#include <string.h>char str[10];  // to store the input stringint used[10];char num[10];  //to store the resultvoid bubbleSort(char* str);void permutation(int pos, int n);int main(int argc, char* argv[]) {  scanf("%s", str);  memset(num, 0, sizeof(num));  memset(used, 0, sizeof(used));  bubbleSort(str);  int len = strlen(str);  permutation(0, len);  return 0;}void bubbleSort(char* str) {  int len = strlen(str);  for (int i = 0; i < len - 1; ++i)    for (int j = 0; j < len - i - 1; ++j)      if (str[j] > str[j + 1]) {        char temp = str[j];        str[j] = str[j + 1];        str[j + 1] = temp;      }}void permutation(int pos, int n) {  static char lastString[10] = "/";  //to store the last legal   if (pos == n) {    if (strcmp(num, lastString) > 0) {      for (int i = 0; i < n; ++i)        printf("%c", num[i]);      printf("\n");      strcpy(lastString, num);    }    return ;  }  for (int i = 0; i < n; ++i) {    if (!used[i]) {      num[pos] = str[i];      used[i] = 1;      permutation(pos + 1, n);      used[i] = 0;    }  }}
0 0
原创粉丝点击