Brace Expansion in C++

C++Server Side ProgrammingProgramming

Suppose we have a string S that represents a list of words. Here each letter in the word has 1 or more options. If there is only one option, the letter is represented as is. If there is more than one option, then curly braces delimit the options. So for example, "{a,b,c}" will represent the options ["a", "b", "c"]. Now for example, if the input is like "{a,b,c}d{e,f}" this will represent the list ["ade", "adf", "bde", "bdf", "cde", "cdf"].

Return all words that can be formed in this manner, in lexicographical order.

To solve this, we will follow these steps −

  • Define an array called ret, define an integer type variable n

  • define a method solve(), this will take index, list and curr as input

  • if index = n, then insert curr into ret and return

  • for i in range 0 to size of list[index]

    • call solve(index + 1, list, curr + list[index, i])

  • From the main method, do the following

  • create a list of size 100, set n := 0, flag := false

  • for i in range 0 to size of s – 1

    • if s[i] is comma, then skip to the next iteration

    • otherwise when s[i] is opening brace, then set flag := true

    • otherwise when s[i] is closing brace, then set flag := false and increase n by 1

    • otherwise increase list[n] by s[i], now if flag is false, then increase n by 1

  • call solve(0, list, empty string)

  • sort the ret array

  • return ret

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
class Solution {
   vector <string> ret;
   int n;
   vector<string> expand(string s) {
      vector <string> list(100);
      n = 0;
      int flag = false;
      for(int i = 0; i < s.size(); i++){
         if(s[i] == ','){
         }else if(s[i] == '{'){
            flag = true;
         }else if(s[i] == '}'){
            flag = false;
            list[n] += s[i];
      solve(0, list);
      sort(ret.begin(), ret.end());
      return ret;
   void solve(int idx, vector <string> list, string curr = ""){
      if(idx == n){
      for(int i = 0; i < list[idx].size(); i++){
         solve(idx + 1, list, curr + list[idx][i]);
   Solution ob;




[acdf, acef, bcdf, bcef, ]
Updated on 30-Apr-2020 15:32:58