C++ 中打印字符的所有排列(含重复)
在这个问题中,我们给定一个包含 n 个字符的字符串,我们需要打印该字符串的所有字符排列。允许重复字符串中的字符。排列的打印应按字母顺序(字典序)进行。
让我们举个例子来更好地理解这个主题
输入 - XY
输出 - XX, XY, YX, YY
为了解决这个问题,我们需要使用固定和递归的逻辑。在这里,我们首先将一个元素固定在数组的第一个索引处,然后递归地调用序列中的下一个元素。
让我们看一个实现示例,它将使解决方案对您更加清晰。
输入字符串 XY。
将第一个元素固定在索引 1 处:X_
递归调用其他元素并填充:XX -> XY
现在将下一个元素固定在索引 1 处:Y_
递归调用其他元素并填充:YX -> YY
相同的逻辑可以用于长度为 3、4、n 的字符串。
示例
#include <iostream>
#include<string.h>
using namespace std;
void printPermutations(char *str, char* permutations, int last, int index){
int i, len = strlen(str);
for ( i = 0; i < len; i++ ) {
permutations[index] = str[i] ;
if (index == last)
cout<<permutations <<"\t";
else
printPermutations (str, permutations, last, index+1);
}
}
int main() {
char str[] = "ABC";
cout<<"All permutations of the string with repetition of "<<str<<" are: "<<endl ;
int len = strlen(str) ;
char permutations[len];
printPermutations (str, permutations, len-1, 0);
return 0;
}输出
All permutations of the string with repetition of ABC are:
AAA AAB AAC ABA ABB ABC ACA ACB ACC BAA BAB BAC BBA BBB BBC BCA BCB BCC CAA CAB CAC CBA CBB CBC CCA CCB CCC
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP