problem:
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"]
Hide Tags
Dynamic Programming Backtracking
thinking:
1 使用二维表vector<vector<int> >tbl记录,记录从i点,能否跳到下一个break位置。如果不能,那么tbl[i]就为空。如果可以,就记录可以跳到哪些位置。
2 利用二维表优化递归回溯法。
优化点:
如果当前位置是start,但是tbl[start]为空,那么就是说,这个break位置不能break整个s串的,直接返回上一层,不用搜索到下一层了。
code:
class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> rs; string tmp; vector<vector<int> > tbl = genTable(s, dict); word(rs, tmp, s, tbl, dict); return rs; } void word(vector<string> &rs, string &tmp, string &s, vector<vector<int> > &tbl, unordered_set<string> &dict, int start=0) { if (start == s.length()) { rs.push_back(tmp); return; } for (int i = 0; i < tbl[start].size(); i++) { string t = s.substr(start, tbl[start][i]-start+1); if (!tmp.empty()) tmp.push_back(' '); tmp.append(t); word(rs, tmp, s, tbl, dict, tbl[start][i]+1); while (!tmp.empty() && tmp.back() != ' ') tmp.pop_back();//tmp.empty() if (!tmp.empty()) tmp.pop_back(); } } vector<vector<int> > genTable(string &s, unordered_set<string> &dict) { int n = s.length(); vector<vector<int> > tbl(n); for (int i = n - 1; i >= 0; i--) { if(dict.count(s.substr(i))) tbl[i].push_back(n-1); } for (int i = n - 2; i >= 0; i--) { if (!tbl[i+1].empty())//if we can break i->n { for (int j = i, d = 1; j >= 0 ; j--, d++) { if (dict.count(s.substr(j, d))) tbl[j].push_back(i); } } } return tbl; } };
时间: 2024-10-03 16:44:15