voidbacktrack(const string& s, int index){ if (!ans.count(index)) { if (index == s.size()) { ans[index] = {""}; return; } ans[index] = {}; for (int i = index + 1; i <= s.size(); ++i) { string word = s.substr(index, i - index); if (wordSet.count(word)) { backtrack(s, i); for (const string& succ: ans[i]) { ans[index].push_back(succ.empty() ? word : word + " " + succ); } } } } } };
[sol1-Python3]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defwordBreak(self, s: str, wordDict: List[str]) -> List[str]: @lru_cache(None) defbacktrack(index: int) -> List[List[str]]: if index == len(s): return [[]] ans = list() for i inrange(index + 1, len(s) + 1): word = s[index:i] if word in wordSet: nextWordBreaks = backtrack(i) for nextWordBreak in nextWordBreaks: ans.append(nextWordBreak.copy() + [word]) return ans wordSet = set(wordDict) breakList = backtrack(0) return [" ".join(words[::-1]) for words in breakList]
structTrie { int ch[26]; bool flag; } trie[10001];
int size;
voidinsert(char* s, int sSize) { int add = 0; for (int i = 0; i < sSize; i++) { int x = s[i] - 'a'; if (trie[add].ch[x] == 0) { trie[add].ch[x] = ++size; memset(trie[size].ch, 0, sizeof(trie[size].ch)); trie[size].flag = false; } add = trie[add].ch[x]; } trie[add].flag = true; }
boolfind(char* s, int sSize) { int add = 0; for (int i = 0; i < sSize; i++) { int x = s[i] - 'a'; if (trie[add].ch[x] == 0) { returnfalse; } add = trie[add].ch[x]; } return trie[add].flag; }
char** ans[1001]; int ansSize[1001];
voidbacktrack(char* s, int sSize, int index) { if (ans[index] == NULL) { ans[index] = malloc(sizeof(char**)); if (index == sSize) { ansSize[index] = 1; char* tmp = malloc(sizeof(char)); tmp[0] = '\0'; ans[index][0] = tmp; return; } ansSize[index] = 0; for (int i = index + 1; i <= sSize; ++i) { int len = i - index; char* word = malloc(sizeof(char) * (len + 1)); for (int j = 0; j < len; ++j) word[j] = s[index + j]; word[len] = '\0'; if (find(word, len)) { backtrack(s, sSize, i); ans[index] = realloc(ans[index], sizeof(char**) * (ansSize[index] + ansSize[i])); for (int j = 0; j < ansSize[i]; ++j) { int len1 = len, len2 = strlen(ans[i][j]); char* tmp = malloc(sizeof(char) * (len1 + len2 + 2)); strcpy(tmp, word); if (len2 > 0) { tmp[len1] = ' '; } strcpy(tmp + len1 + 1, ans[i][j]); ans[index][ansSize[index]++] = tmp; } } } } }