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