字典树+dfs就完事了
class Solution { public: int tree[10010][26]; bool vis[10010]; int cnt; vector<string> v; void build(string str) { int len = str.length(); int rt = 0; for(int i = 0; i < len; i++) { int x = str[i] - 'a'; if(tree[rt][x] == 0) { tree[rt][x] = ++cnt; } rt = tree[rt][x]; } vis[rt] = 1; } void dfs(string s, int k, string str) { if(k >= s.length()) { v.push_back(str); return; } int rt = 0; int len = s.length(); string tmp = ""; while(k < len) { int x = s[k] - 'a'; rt = tree[rt][x]; if(rt == 0) break; tmp += s[k]; if(vis[rt]) dfs(s, k + 1, str == "" ? str + tmp : str + " " + tmp); k++; } } vector<string> wordBreak(string s, vector<string>& wordDict) { cnt = 0; memset(vis, 0, sizeof(vis)); memset(tree, 0, sizeof(tree)); int len = wordDict.size(); for(int i = 0; i < len; i++) { build(wordDict[i]); } dfs(s, 0, ""); return v; } };