LeetCode——Word Break II

来源:互联网 发布:顶点软件股票牛叉诊股 编辑:程序博客网 时间:2024/06/06 14:09

Word Break II

Given a string s and a dictionary of words dict, add spaces ins 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"].

思路:
本题可采用DP+DFS解决。
DP:定义状态vector<vecotor<int> > dp;dp[i]存储一个整数数组,那么dp[i][j]表示:s.sbustr(dp[i][j],i-dp[i][j])为字典中的词。
DFS:根据DP中的索引值,比较容易写出DFS代码。
代码:
class Solution {public:vector<string> wordBreak(string s, unordered_set<string> &dict) {if (s == "")return vector<string>();dp.assign(s.length() + 1, vector<int>());dp[0].push_back(-1);for (int i = 0; i < s.length(); i++) {if (dp[i].size() == 0)continue;for (int j = 1; i + j <= s.length(); j++) {if (dict.find(s.substr(i, j)) != dict.end()) {dp[i + j].push_back(i);}}}vector<string> ret;string tmp = "";dfs(ret, tmp, s, s.length());return ret;}private:vector<vector<int> > dp;void dfs(vector<string> &ret, string tmp, string &s, int cur) {if (cur == 0) {ret.push_back(tmp);return;}for (int i = 0; i < dp[cur].size(); i++) {if (cur == s.length()) {dfs(ret, s.substr(dp[cur][i], cur - dp[cur][i]), s, dp[cur][i]);} else {dfs(ret, s.substr(dp[cur][i], cur - dp[cur][i]) + " " + tmp, s,dp[cur][i]);}}}};


0 0