我们用一个特殊的字符串 S 来表示一份单词列表,之所以能展开成为一个列表,是因为这个字符串 S 中存在一个叫做「选项」的概念:
单词中的每个字母可能只有一个选项或存在多个备选项。如果只有一个选项,那么该字母按原样表示。
如果存在多个选项,就会以花括号包裹来表示这些选项(使它们与其他字母分隔开),例如 "{a,b,c}" 表示 ["a", "b", "c"]。
输入: "{a,b}c{d,e}f"
输出: ["acdf","acef","bcdf","bcef"]
class Solution {
public:
vector<string> expand(string s) {
for (int i = 0; i < s.size(); i++) { // 处理字符串使其便于dfs
if (s[i] == ‘,‘) continue;
if (s[i] == ‘{‘) {
string cur;
while (s[++i] != ‘}‘)
if (s[i] != ‘,‘) cur.push_back(s[i]);
sort(cur.begin(), cur.end());
chs.push_back(cur);
}
else chs.push_back(string(1, s[i]));
}
dfs(0);
return res;
}
private:
vector<string> chs, res;
string ans;
void dfs(int pos) {
if (pos == chs.size()) {
res.push_back(ans);
return;
}
for (char ch : chs[pos]) {
ans.push_back(ch);
dfs(pos + 1);
ans.pop_back();
}
}
};
举个例子,将{a, b} c {d, e} f
展开为{a, b} {c} {d, e} {f}
,然后就可以DFS了。
原文:https://www.cnblogs.com/tmpUser/p/14617104.html