## Tuesday, June 7, 2016

### Print all ways to break a string in bracket form - GeeksforGeeks

Print all ways to break a string in bracket form - GeeksforGeeks
Given a string, find all ways to to break the given string in bracket form. Enclose each substring within a parenthesis.

```Input : abc
Output: (a)(b)(c)
(a)(bc)
(ab)(c)
(abc)```

The idea is to use recursion. We maintain two parameters – index of the next character to be processed and the output string so far. We start from index of next character to be processed, append substring formed by unprocessed string to the output string and recurse on remaining string until we process the whole string. We use std::substr to form the output string. substr(pos, n) returns a substring of length n that starts at position pos of current string.
Below diagram shows recursion tree for input string “abc”. Each node on the diagram shows processed string (marked by green) and unprocessed string (marked by red).
`void` `findCombinations(string str, ``int` `index,`
`                      ``string out)`
`{`
`    ``if` `(index == str.length())`
`        ``cout << out << endl;`
`    ``for` `(``int` `i = index; i < str.length(); i ++)`
`        ``// append substring formed by str[index,`
`        ``// i] to output string`
`        ``findCombinations(str, i + 1, out +`
`          ``"("` `+ str.substr(index, i+1-index) + ``")"` `);`
`}`

Exponential i.e. O(2^n) where n is length of the input string. Before you ask for polynomial time solution please note there are 2^(n-1) combinations in the output.