題目描述
給定一個非空字符串 s 和一個包含非空單詞列表的字典 wordDict,在字符串中增加空格來構建一個句子,使得句子中所有的單詞都在詞典中。返回所有這些可能的句子。
說明:
分隔時可以重複使用字典中的單詞。
你可以假設字典中沒有重複的單詞。
示例 1:
輸入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
輸出:
[
"cats and dog",
"cat sand dog"
]
示例 2:
輸入:
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
輸出:
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解釋: 注意你可以重複使用字典中的單詞。
示例 3:
輸入:
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
輸出:
[]
來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/word-break-ii
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。
白話題目:
算法:
詳細解釋關注 B站 【C語言全代碼】學渣帶你刷Leetcode 不走丟 https://www.bilibili.com/video/BV1C7411y7gB
C語言完全代碼
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
#define MAX_SIZE 1024
void dfs(char *s, int pos, char **res, int *returnSize, char **wordDict, int wordDictSize, int *result, int idx, int *fail)
{
if (s[pos] == '\0') { //得到一個結果
// 先算長度
int length = 0;
for (int i = 0; i < idx; ++i) {
length += strlen(wordDict[result[i]]) + 1;
}
res[*returnSize] = (char *)malloc(length * sizeof(char));
int p = 0;
for (int i = 0; i < idx; i++) {
for (int j = 0; j < strlen(wordDict[result[i]]); j++) {
res[*returnSize][p++] = wordDict[result[i]][j];
}
res[*returnSize][p++] = ' ';
}
res[*returnSize][length - 1] = '\0';
(*returnSize)++;
return;
}
//如果pos位置失敗,直接跳過
if (fail[pos] == 1) {
return;
}
// 如果遍歷完wordDict,未能匹配,fail[pos] 置 1
int fail_cnt = 0; //記錄pos位置匹配wordDict 失敗的計數,如果pos位置無法匹配wordDict裏所有單詞,則fail[pos] = 1
for (int i = 0; i < wordDictSize; i++) {
if (pos == 0) {
memset(fail, 0, MAX_SIZE * sizeof(int));
}
int len = strlen(wordDict[i]);
if (fail[pos + len] == 1) { // 這裏加判斷!!!!如果pos + len 位置不滿足,那麼pos位置匹配完這個單詞也不會滿足
fail_cnt++;
continue;
}
if (strlen(s) - pos >= len && memcmp(s + pos, wordDict[i], len) == 0) {
result[idx] = i; //匹配到單詞,記錄在result裏
dfs(s, pos + len, res, returnSize, wordDict, wordDictSize, result, idx + 1, fail);
} else {
fail_cnt++; // 這裏判斷一下
}
}
if (fail_cnt == wordDictSize) {
fail[pos] = 1;
}
return;
}
char ** wordBreak(char * s, char ** wordDict, int wordDictSize, int* returnSize){
size_t len = strlen(s);
char **res = (char **)malloc(sizeof(char *) *MAX_SIZE);
*returnSize = 0;
int *result = (int *)malloc(len * sizeof(int));
memset(result, -1, len * sizeof(int));
int *fail = (int *)calloc(MAX_SIZE, sizeof(int));
dfs(s, 0, res, returnSize, wordDict, wordDictSize, result, 0, fail);
return res;
}