在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 新房祝福语简短10字
14 长辈新年祝福语大全简短
15 新年给大家简短祝福语
16 生日祝福语简短独特姑姑
17 芭比的婚礼祝福语简短
18 邀请新人祝福语简短英文