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.
Read full article from 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) +
")"
);
}
Read full article from Print all ways to break a string in bracket form - GeeksforGeeks