ในปัญหานี้ เราได้รับสตริงและต้องพิมพ์สตริงทั้งหมดที่สามารถสร้างโดยใช้สตริงนี้โดยวางช่องว่างระหว่างอักขระของสตริง
มาดูตัวอย่างเพื่อทำความเข้าใจหัวข้อกันดีกว่า −
Input: string = ‘XYZ’ Output: XYZ, XY Z, X YZ, X Y Z
เพื่อแก้ปัญหานี้ เราจะต้องค้นหาวิธีที่เป็นไปได้ทั้งหมดที่เราสามารถใส่ช่องว่างในสตริงได้ สำหรับสิ่งนี้เราจะใช้การเรียกซ้ำ ในส่วนนี้ เราจะใส่ช่องว่างทีละหนึ่งและสร้างสตริงใหม่
ตัวอย่าง
#include <iostream>
#include <cstring>
using namespace std;
void printPattern(char str[], char buff[], int i, int j, int n){
if (i==n){
buff[j] = '\0';
cout << buff << endl;
return;
}
buff[j] = str[i];
printPattern(str, buff, i+1, j+1, n);
buff[j] = ' ';
buff[j+1] = str[i];
printPattern(str, buff, i+1, j+2, n);
}
int main() {
char *str = "XYZ";
int n = strlen(str);
char buf[2*n];
buf[0] = str[0];
cout<<"The string generated using space are :\n";
printPattern(str, buf, 1, 1, n);
return 0;
} ผลลัพธ์
สตริงที่สร้างขึ้นโดยใช้ช่องว่างคือ −
XYZ XY Z X YZ X Y Z