在C ++中以字符重复打印所有排列
在这个问题中,我们给了一个n个字符的字符串,并且我们必须打印该字符串的所有字符排列。允许重复字符串的字符。排列的打印应按字母顺序(按字母顺序排序)进行。
让我们举个例子来更好地理解这个话题:
输入:XY
输出:XX,XY,YX,YY
要解决此问题,我们需要使用修复和递归逻辑。在这里,我们将在数组的第一个索引处固定一个元素,然后递归调用序列中的下一个元素。
让我们看一个实现示例,它将使您的解决方案清晰明了。
输入字符串XY。
将第一个元素固定在1索引处:X_
递归调用其他元素并填充:XX->XY
现在将下一个元素固定在index1: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
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志