在这个问题中,我们得到了一个字符串,我们必须将其分解为子字符串并在其周围加上括号。
让我们举几个例子来更好地理解问题,
Input : wxyz Output : (w) (x) (y) (z) (w) (x) (yz) (w) (xy) (z) (w) (xyz) (wx) (y) (z) (wx) (yz) (wxy) (z) (wxyz)
说明-我们将字符串分成所有可能的子字符串。并将每个子字符串括在方括号中。
现在,既然我们已经了解了问题,那么让我们为该问题创建一个解决方案。
在这里,我们将使用递归来解决问题。我们将使用两个参数,一个是字符串的下一个字符,另一个是输出字符串。未处理的子字符串将在每次迭代时缓慢地进行处理。并创建了子集。
解决问题的程序-
#include <iostream>
using namespace std;
void substring(string str, int index, string out){
if (index == str.length())
cout << out << endl;
for (int i = index; i < str.length(); i++)
substring(str, i + 1, out + "(" + str.substr(index, i+1-index) + ")" );
}
int main(){
string str = "wxyz";
cout<<”The substring are :”<<endl;
substring(str, 0, "");
return 0;
}输出结果
The substring are : (w)(x)(y)(z) (w)(x)(yz) (w)(xy)(z) (w)(xyz) (wx)(y)(z) (wx)(yz) (wxy)(z) (wxyz)