이 문제에서 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