标签:style blog class code java color
class Solution { private: vector<string> result; public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<vector<int> > dp; result.clear(); int len = s.length(); dp.resize(len + 1); dp[0].push_back(-1); for (int i=1; i<=len; i++) { for (int j=i-1; j>=0; j--) { string str = s.substr(j, i - j); if (dict.find(str) != dict.end()) { if (dp[j].empty()) continue; dp[i].push_back(j); } } } dfs_build(dp, s, len, ""); return result; } void dfs_build(vector<vector<int> >& dp, string& s, int len, string sent) { vector<int> indices = dp[len]; for (int i=0; i<indices.size(); i++) { int prefix_len = indices[i]; if (prefix_len <= 0) { result.push_back(s.substr(0, len) + sent); } else { string suffix = s.substr(prefix_len, len - prefix_len); dfs_build(dp, s, prefix_len, " " + suffix + sent); } } } };
首先直接用dp构建结果,就是dp数组的类型是vector<vector<string> >,每个外层元素表示某一长度内的所有可分词情况,然后读入一个字母遍历原来的状态,如果新的组合可以则保存,但是这样会超内存,于是把dp数组改为只保存上一个可分词的长度(等同于原先字符串中的索引位置),然后用一个dfs构建出最终的结果,时间在80+ms应该不算暴力了吧。下面给出memory limit exceed的代码,好理解一些
class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<vector<string> > dp; int len = s.length(); dp.resize(len + 1); dp[0].push_back(""); for (int i=1; i<=len; i++) { for (int j=i-1; j>=0; j--) { string str = s.substr(j, i - j); if (dict.find(str) != dict.end()) { vector<string>& prefix = dp[j]; if (prefix.empty()) continue; for (int k=0; k<prefix.size(); k++) { if (prefix[k].length() == 0) { dp[i].push_back(str); } else { dp[i].push_back(prefix[k] + " " + str); } } } } } vector<string> ret = dp[len]; dp.clear(); return ret; } };
LeetCode Word Break II,布布扣,bubuko.com
标签:style blog class code java color
原文地址:http://www.cnblogs.com/lailailai/p/3714660.html