1087. Brace Expansion
Input: "{a,b}c{d,e}f"
Output: ["acdf","acef","bcdf","bcef"]Input: "abcd"
Output: ["abcd"]// Recursive Backtracking
void helper(const string& s, int idx, string& cur, vector<string>& res) {
if (idx == s.length()) {
if (!cur.empty()) res.push_back(cur);
return;
}
char c = s[idx];
if (c == '{') {
string chars; // potential character options
int curIdx = idx + 1;
while (curIdx < s.length() && s[curIdx] != '}') {
if (s[curIdx] >= 'a' && s[curIdx] <= 'z') chars.push_back(s[curIdx]);
++curIdx;
}
// sorting for lexicographical order
sort(chars.begin(), chars.end());
// backtracking
for (char ch : chars) {
cur.push_back(ch);
helper(s, curIdx + 1, cur, res);
cur.pop_back();
}
} else if (c >= 'a' && c <= 'z') {
cur.push_back(c);
helper(s, idx + 1, cur, res);
cur.pop_back();
}
}
vector<string> expand(string S) { // time: O(2^n); space: O(n)
string cur;
vector<string> res;
helper(S, 0, cur, res);
return res;
}Last updated