Given a string, break it into all possible combinations of non-overlapping substrings enclosed within curly brackets.

Please note that the problem specifically targets substrings that are contiguous (i.e., occupy consecutive positions) and inherently maintains the order of elements.

 
For example,

Input: ABC
 
Output:
 
{ABC}
{AB}{C}
{A}{BC}
{A}{B}{C}
 
 
Input: ABCD
 
Output:
 
{ABCD}
{ABC}{D}
{AB}{CD}
{AB}{C}{D}
{A}{BCD}
{A}{BC}{D}
{A}{B}{CD}
{A}{B}{C}{D}

We can use recursion to solve this problem. The idea is to maintain two parameters – the index of the next character to be processed and the result string so far. We start from the index of the next character to be processed, append the substring formed by the unprocessed string to the result string and recur on the remaining string until the whole string is processed.

The following diagram represents a recursion tree for string abc. In each tree node, the processed part is shown by the green color, and the red color shows the unprocessed string.

        Non overlapping substrings

 
Following is the C++, Java, and Python implementation based on the above idea:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
{ABCD}
{ABC}{D}
{AB}{CD}
{AB}{C}{D}
{A}{BCD}
{A}{BC}{D}
{A}{B}{CD}
{A}{B}{C}{D}

The time complexity of the above solution is exponential and requires additional space for the recursion (call stack).

 
Author: Aditya Goel