您的位置:首页 > 其它

[LeetCode] WordBreak II, Solution

2013-11-21 12:17 393 查看
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"]
. [Thoughts] 既然是要给出所有解,那就递归好了,但是递归的过程中注意剪枝。
  没有剪枝版

[code]     vector<string> wordBreak(string s, unordered_set<string> &dict) {
string result;
vector<string> solutions;
int len = s.size();
GetAllSolution(0, s, dict, len, result, solutions);
return solutions;
}

void GetAllSolution(int start, const string& s, const unordered_set<string> &dict, int len, string& result, vector<string>& solutions)
{
if (start == len)
{
solutions.push_back(result.substr(0, result.size()-1));//eliminate the last space
return;
}
for (int i = start; i< len; ++i)
{
string piece = s.substr(start, i - start + 1);
if (dict.find(piece) != dict.end() && possible[i+1])
{
result.append(piece).append(" ");
GetAllSolution(i + 1, s, dict, len, result, solutions);
result.resize(result.size() - piece.size()-1);
}
}
}

但是很明显,这种裸的递归,效率太低,因为有大量的重复计算,肯定过不了测试数据。
剪枝版
这里加上一个possible数组,如同WordBreak I里面的DP数组一样,用于记录区间拆分的可能性

Possible[i] = true 意味着 [i,n]这个区间上有解

加上剪枝以后,运行时间就大大减少了。(Line 5, 20, 23, 25,26为剪枝部分)

vector<string> wordBreak(string s, unordered_set<string> &dict) {
string result;
vector<string> solutions;
int len = s.size();
vector<bool> possible(len+1, true); // to record the search which has been executed once
GetAllSolution(0, s, dict, len, result, solutions, possible);
return solutions;
}

void GetAllSolution(int start, const string& s, const unordered_set<string> &dict, int len, string& result, vector<string>& solutions, vector<bool>& possible)
{
if (start == len)
{
solutions.push_back(result.substr(0, result.size()-1));//eliminate the last space
return;
}
for (int i = start; i< len; ++i)
{
string piece = s.substr(start, i - start + 1);
if (dict.find(piece) != dict.end() && possible[i+1]) // eliminate unnecessory search
{
result.append(piece).append(" ");
int beforeChange = solutions.size();
GetAllSolution(i + 1, s, dict, len, result, solutions, possible);
if(solutions.size() == beforeChange) // if no solution, set the possible to false
possible[i+1] = false;
result.resize(result.size() - piece.size()-1);
}
}
}

suoyi
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: