
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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) (wxyz)
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.
Example
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; }
Output
The substring are : (w)(x)(y)(z) (w)(x)(yz) (w)(xy)(z) (w)(xyz) (wx)(y)(z) (wx)(yz) (wxy)(z) (wxyz)
- Related Articles
- Print all possible ways to convert one string into another string in C++
- Print Bracket Number in C++
- C++ Program to find number of RBS string we can form bracket sequences
- Print all subsequences of a string in C++
- Print all permutations of a string in Java
- Print all funny words in a string in C++
- Program to print all substrings of a given string in C++
- Print all palindromic partitions of a string in C++
- Print all palindrome permutations of a string in C++
- Program to find number of ways to form a target string given a dictionary in Python
- Print all permutations of a given string
- Print all distinct characters of a string in order in C++
- Print all permutation of a string using ArrayList in Java
- Print all subsequences of a string using ArrayList in C++
- Print all triplets in sorted array that form AP in C++

Advertisements