Leetcode dfs Word Break II,leetcodedfs

來源:互聯網
上載者:User

Leetcode dfs Word Break II,leetcodedfs


Word Break II Total Accepted: 15138 Total Submissions: 92228My Submissions

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"].



題意:
給定一個字串和一個單詞字典,找出可以用字典裡的單詞來分割這個字串的各種組合。
思路:dfs 
void dfs(int start, string partition);
start表示當前要分割的字串s[start:],
設 k將 s分割為s[:k]和s[k:],則 0 < k <= s.size() 且 s[:k]存在字典dict中
按上面這樣的思路直接做會逾時,可採用dfs + 剪枝的思路
增加一個bool數組 possible[k] 表示字串s[k:]是否可用字典裡的單詞來分割


unordered_set<string> _dict;vector<string> res;vector<bool> possible;string _s;void dfs(int start, string partition){if(start >= _s.size()){res.push_back(partition.substr(1, partition.size() - 1));return;}for(int k = start + 1; k <= _s.size(); ++k){if(possible[k] &&  _dict.find(_s.substr(start, k  - start)) != _dict.end()){ //剪枝int size_before = res.size();dfs(k , partition + " " + _s.substr(start, k  - start));if(res.size() == size_before) possible[k] = false; //剪枝}}}vector<string> wordBreak(string s, unordered_set<string> &dict){_dict = dict;_s = s;possible = vector<bool>(s.size() + 1, true);dfs(0, "");return res;}





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.