国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計(jì) > 正文

Leetcode 139 - Word Break(線性dp)

2019-11-11 04:03:59
字體:
供稿:網(wǎng)友

題意

給一個(gè)字符串S和一個(gè)字典WordDict,要求判斷是否能用wordDict內(nèi)的數(shù)組成S。

思路

算法1

區(qū)間dp,時(shí)間復(fù)雜度O(n3)

首先將wordDict內(nèi)的字符串全部丟到unordered_set<string> has里面,方便查看有沒有。

狀態(tài)表示d[i,j],區(qū)間s[i, j]能否用has內(nèi)的字符串表示。

轉(zhuǎn)移方程d[i,j]=d[i,k]&&d[k+1,j]

算法2

線性dp,時(shí)間復(fù)雜度O(n2)

狀態(tài)表示d[i],區(qū)間s[0, i]能夠用has內(nèi)的字符串表示。

轉(zhuǎn)移方程

s[0,i]能用has表示:d[i]=1s[j+1,i]能用has內(nèi)的字符串表示且d[j]==1d[i]=1其他情況:d[i]=0

代碼

//n^3 dpconst int maxn = 1005;class Solution {public: unordered_map<string, int> has; int d[maxn][maxn]; int dfs(int i, int j, string s) { if (i > j) return 0; if (d[i][j] != -1) return d[i][j]; if (has.find(s.substr(i, j - i + 1)) != has.end()) return d[i][j] = 1; d[i][j] = 0; for (int k = i; k < j; k++) { int t1 = dfs(i, k, s), t2 = dfs(k + 1, j, s); if (t1 == 1 && t2 == 1) d[i][j] = 1; else d[i][j] = 0; if (d[i][j] == 1) { return d[i][j]; } } return d[i][j]; } bool wordBreak(string s, vector<string>& wordDict) { if (wordDict.size() == 0) return s == ""; for (auto x : wordDict) { if (has.find(x) == has.end()) has[x] = 1; } memset(d, -1, sizeof(d)); return dfs(0, s.size() - 1, s); }};//n^2 dpclass Solution {public: unordered_set<string> has; bool wordBreak(string s, vector<string>& wordDict) { if (wordDict.empty()) return s == ""; for (auto x : wordDict) has.insert(x); vector<bool> d(s.length(), 0); string t = s.substr(0, 1); d[0] = (has.find(t) == has.end() ? 0 : 1); for (int i = 1; i < s.length(); i++) { string t = s.substr(0, i + 1); if (has.find(t) != has.end()) { d[i] = true; continue; } for (int j = 0; j < i; j++) { if (d[j]) { string tt = s.substr(j + 1, i - j); if (has.find(tt) != has.end()) d[i] = true; } } } return d[s.length() - 1]; }};
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 盘锦市| 宝丰县| 湘阴县| 万安县| 阳春市| 富川| 临邑县| 太和县| 临潭县| 东乡| 平昌县| 沛县| 綦江县| 绥中县| 南乐县| 南川市| 高青县| 弥勒县| 富平县| 海城市| 高尔夫| 连城县| 纳雍县| 岑巩县| 上饶市| 偏关县| 会宁县| 富民县| 河东区| 万盛区| 搜索| 安徽省| 裕民县| 中方县| 广安市| 都江堰市| 万山特区| 芷江| 临沧市| 桃园市| 珠海市|