How to print all possible ways to break a string in brackets with C++

1 Answer

0 votes
#include <iostream>

void break_string_in_bracket(std::string str, int index, std::string form) {
    if (index == str.length()) {  
        std::cout << form << "\n";
    }
  
    for (int i = index; i < str.length(); i++) {
        std::string temp = form;
        temp += "(";
        temp += str.substr(index, i + 1 - index);
        temp += ")";
        break_string_in_bracket(str, i + 1, temp);
    }
}

int main()
{
    std::string str = "abcd";
  
    break_string_in_bracket(str, 0, "");
}




/*
run:

(a)(b)(c)(d)
(a)(b)(cd)
(a)(bc)(d)
(a)(bcd)
(ab)(c)(d)
(ab)(cd)
(abc)(d)
(abcd)

*/

 



answered Aug 26, 2023 by avibootz
...