在 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
广告