Print all ways to break a string in bracket form in C++

In this problem, we are given a string and we have to break it into substrings and print them enclosing brackets.

Let’s take a few examples to understand the problem better,

Input : wxyz
Output :
   (w) (x) (y) (z)
   (w) (x) (yz)
   (w) (xy) (z)
   (w) (xyz)
   (wx) (y) (z)
   (wx) (yz)
   (wxy) (z)

Explanation − We will break the string into all possible substrings. And enclose each substring with brackets.

Now, since we have understood the problem, let’s create a solution to the problem.

Here, we will use recursion to solve the problem. We will use two parameters, one will be the next character of the string and the other is the output string. The unprocessed substring will slowly be processed at each iteration. And the subsets are created.


Program to solve the problem −

#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 :