ในปัญหานี้ เราได้รับสตริงอักขระ 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