用 C++ 打印给定字符串的所有不同排列,其中包含重复项
在此问题中,我们给定了一个可能包含重复字符的字符串。我们的任务是打印字符串的所有不同排列。
让我们举个例子来理解问题 −
Input: string = “XYZ” Output: XYZ XZY YXZ YZX ZYX ZXY
为了解决这个问题,我们必须固定字符串的一个元素。然后迭代字符串的所有元素。
示例
实现我们解决方案的程序,
#include <string.h>
#include <iostream>
using namespace std;
int compare(const void* a, const void* b) {
return (*(char*)a - *(char*)b);
}
void swapChar(char* a, char* b) {
char t = *a;
*a = *b;
*b = t;
}
int findCeil(char str[], char first, int l, int h) {
int ceilIndex = l;
for (int i = l + 1; i <= h; i++)
if (str[i] > first && str[i] < str[ceilIndex])
ceilIndex = i;
return ceilIndex;
}
void printPermutations(char str[]) {
int size = strlen(str);
qsort(str, size, sizeof(str[0]), compare);
bool isFinished = false;
while (!isFinished) {
static int x = 1;
cout<<str<<"\t";
int i;
for (i = size - 2; i >= 0; --i)
if (str[i] < str[i + 1])
break;
if (i == -1)
isFinished = true;
else {
int ceilIndex = findCeil(str,
str[i], i + 1, size - 1);
swapChar(&str[i], &str[ceilIndex]);
qsort(str + i + 1, size - i - 1,
sizeof(str[0]), compare);
}
}
}
int main() {
char str[] = "SNGY";
cout<<"All permutations of the string"<<str<<" are :\n";
printPermutations(str);
return 0;
}输出
All permutations of the stringSNGY are − GNSY GNYS GSNY GSYN GYNS GYSN NGSY NGYS NSGY NSYG NYGS NYSG SGNY SGYN SNGY SNYG SYGN SYNG YGNS YGSN YNGS YNSG YSGN YSNG
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP