LeetCode,leetcodeoj

來源:互聯網
上載者:User

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;   }           }          }   }   }


著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.