@LIUHUAN
2020-02-02T10:22:04.000000Z
字数 2867
阅读 839
algorithm
unordered_map<string, int> umap;
bool wordbreak(string s, vector<string>& wordDict)
{
int n = s.size();
for (auto& e : wordDict)
umap[e] = 1;
return wordBreak2(s, 0, n - 1);
}
bool wordBreak2(string s, int i, int j)
{
int n = s.size();
if (i > j || j >= n) // base case #1
return 0;
string str = string(s.begin() + i, s.begin() + j + 1);
if (umap.find(str) != umap.end()) { // base case #2
return 1;
}
for (int k = i; k < j; ++k) {
int x = wordBreak2(s, i, k);
if (!x)// prune for false substr s[i,k]
continue;
int y = wordBreak2(s, k + 1, j);
if (x && y)
return 1;
}
return 0;
}
map
,也可以用数组,来缓存已经计算完的数据。对于已经获取的数据直接返回结果。map
来保存,例如map[0-10]=1
,表示的子串,是否可分割。
unordered_map<string, int> umap;
unordered_map<string, int> rmap;
bool wordbreak3(string s, vector<string>& wordDict)
{
int n = s.size();
for (auto& e : wordDict)
umap[e] = 1;
return wordBreak2(s, 0, n - 1);
}
bool wordBreak3(string s, int i, int j)
{
int n = s.size();
if (i > j || j >= n)
return 0;
string key = to_string(i) + "-" + to_string(j);
if (rmap.find(key) != rmap.end()) {// has cached result s[i,j]
return rmap[key];
}
string str = string(s.begin() + i, s.begin() + j + 1);
if (umap.find(str) != umap.end()) { // base case for w in dictionary
rmap[key] = 1;
return 1;
}
for (int k = i; k < j; ++k) {
int x = wordBreak2(s, i, k);
if (!x)// prone the result s[i,k]
continue;
int y = wordBreak2(s, k + 1, j);
if (x && y) {
rmap[key] = 1; //cache result s[i,j]
return 1;
}
}
rmap[key] = 0;// cache result s[i,j]
return 0;
}
bool wordBreak(string s, vector<string>& wordDict)
{
for (auto& e : wordDict)
umap[e] = 1;
int n = s.size();
int f = 0;
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int l = 0; l <= n; l++) {
for (int i = 0; i < n - l; i++) {
int j = i + l;
if (j >= n)
break;
string str(s.begin() + i, s.begin() + j + 1);
if (umap.find(str) != umap.end()) {
dp[i][j] = 1;
f = 1;
}
}
}
if (f == 0) {
return 0;
}
if(dp[0][n-1])
return 1;
for (int l = 0; l < n; l++) {
for (int i = 0; i < n - l; ++i) {
int j = i + l;
if (dp[i][j] == 1)
continue;
for (int k = i; k < j; ++k) {
int c = dp[i][k] && dp[k + 1][j];
dp[i][j] = max(c, dp[i][j]);
if (dp[i][j])
break;
}
}
}
return dp[0][n - 1];
}