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
- LeetCode——Word Break II
- LeetCode — Word Break II 解题报告
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Leetcode: Word Break II
- LeetCode Word Break II
- Word Break II leetcode
- VS2010在加载项目时,提示无法打开项目文件, 此安装不支持该项目类型的解决方法
- 11周项目二
- 11-1存储班长信息的学生类(拓展)
- 你是我信仰里的一束光
- 简单动画
- LeetCode——Word Break II
- centos下rpm安装mysql5.6(二)
- 职员有薪水了
- 11周项目1
- list排序方法
- c++0x_warning.h:31:2: error
- 循环冗余校验(CRC)算法入门引导
- CCNA 精简笔记
- 【项目1 - 存储班长信息的学生类】