#include <iostream>
#include <unordered_set>
#include <vector>
#include <string.h>
using namespace std;
/*
与139题类似,但是在139只是判断的基础上还要返回所有划分的结果,
由于要返回字符串,所以要多用一个二维的表作为备忘表,如果最右一列
有一个是true就说明是有匹配的,但是还要加一个深搜的过程,找出所有
符合条件的字符串。
*/
class Solution {
//这是从左上角到右下角扫描,所以超时,试一下反过来
// void dfs(vector<string> &svec, vector<string> &wvec, int ind, string s, const vector<vector<bool>> &m) {
// if (ind == s.length()) {
// string addstr = "";
// for (auto i = 0; i < wvec.size() - 1; i++) {
// addstr += wvec[i] + " ";
// }
// addstr += wvec.back();
// svec.push_back(addstr);
// }
// for (int i = ind + 1; i < s.length() + 1; i++) {
// if (m[ind][i] == true) {
// wvec.push_back(s.substr(ind, i - ind));
// dfs(svec, wvec, i, s, m);
// wvec.pop_back();
// }
// }
// }
//额,换了顺序就过了。。。
void dfs(vector<string> &svec, vector<string> &wvec, int ind, string s, const vector<vector<bool>> &m) {
if (ind == 0) {
string addstr = "";
for (auto i = wvec.size() - 1; i > 0; i--) {
addstr += wvec[i] + " ";
}
addstr += wvec.front();
svec.push_back(addstr);
}
for (int i = ind - 1; i >= 0; i--) {
if (m[i][ind] == true) {
wvec.push_back(s.substr(i, ind - i));
dfs(svec, wvec, i, s, m);
wvec.pop_back();
}
}
}
public:
//>>一定要用空格隔开
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<vector<bool> > memo(s.length() + 1, vector<bool>(s.length() + 1, false));
vector<bool> rec(s.length() + 1, false);
rec[0] = true;
int len = s.length();
for (int i = 0; i < len; i++) {
for (int j = len; j > i; j--) {
if (rec[i] == true && wordDict.find(s.substr(i, j - i)) != wordDict.end()) {
rec[j] = true;
memo[i][j] = true;
}
}
}
vector<string> stringvct, wordvect;
dfs(stringvct, wordvect, len, s, memo);
return stringvct;
}
};
//"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab"
//["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]
//"catsanddog"
//["cat","cats","and","sand","dog"]
int main(int argc, const char * argv[]) {
Solution s;
unordered_set<string> myset({"cat","cats","and","sand","dog"});
vector<string> result = s.wordBreak("catsanddog", myset);
cout << result.size() << endl;
for (auto i = 0; i < result.size(); i++) {
cout << result[i] << endl;
}
return 0;
}
leetcode-140-Word Break II
最新推荐文章于 2020-05-30 04:35:44 发布