LeetCode,leetcodeoj
題目描述:
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].
給定1個字串s,和一個字典(字串數組),對s進行分詞,求出所有可能情況。
從題目本身來看,本題的解法是一個DFS,拿到s.substr[0...n],如果在dic中存在,則拿到當前index對s.substr[index...n]遞迴執行,如果s在dic中找到,添加到結果集。 由於沒有剪枝,存在很多不必要的遞迴。
剪枝:可以使用長度為s.Length的數組來存放s在每一位是否存在可能解。在繼續遞迴之前,把當前的解集存一下,遞迴之後,解集沒有改變,說明沒有繼續執行的必要。
實現代碼:
public IList<string> WordBreak(string s, ISet<string> wordDict) {var results = new List<string>();var possible = new bool[s.Length];for(var i = 0;i < possible.Length; i++){possible[i] = true;}DfsWithCut(0,s, wordDict, "", results, possible);return results; }public void DfsWithCut(int start , string s, ISet<string> wordDic, string result, IList<string> results, bool[] possible){var left = s.Substring(start , s.Length - start);if(wordDic.Any(x=> x == left)){var r = result == "" ? left : result + " " + left;results.Add(r);} for(var i = start ;i < s.Length ; i++){ var w = s.Substring(start, i - start + 1); if(wordDic.Any(x=>x == w) && i < s.Length - 1){ if(possible[i+1] /*only if possible do recursion*/){ var r = result == "" ? w : result + " " + w; var before = results.Count; // track current results count before dfs DfsWithCut(i + 1, s , wordDic, r, results, possible); if(results.Count == before){ // since no new result found , mark possible[i+1] as false to cut it possible[i+1] = false; } } } } }
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。