在 C++ 中列印可以透過在字串中放置空格生成的所有可能的字串
在這個問題中,給定一個字串,我們需要打印出可以透過在字串字元間放置空格而生成的字串。
我們舉個例子來更好地理解這個主題 -
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP