# Brace Expansion in C++

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

• 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 {
public:
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] == ','){
continue;
}else if(s[i] == '{'){
flag = true;
}else if(s[i] == '}'){
flag = false;
n++;
}else{
list[n] += s[i];
if(!flag)n++;
}
}
solve(0, list);
sort(ret.begin(), ret.end());
return ret;
}
void solve(int idx, vector <string> list, string curr = ""){
if(idx == n){
ret.push_back(curr);
return;
}
for(int i = 0; i < list[idx].size(); i++){
solve(idx + 1, list, curr + list[idx][i]);
}
}
};
main(){
Solution ob;
print_vector(ob.expand("{a,b}c{d,e}f"));
}

### Input

"{a,b}c{d,e}f"

## Output

[acdf, acef, bcdf, bcef, ]