LeetCode-Word Break II
来源:互联网 发布:战龙三国张郺进阶数据 编辑:程序博客网 时间:2024/06/05 03:07
Given a string s and a dictionary of words dict, add spaces in s 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"]
.
Code:
<span style="font-size:14px;">class Solution {public: void DFS(vector<string> &results, const vector<vector<int> > &dp, int index, string result, const string &s) { const int length = dp[index].size(); if (length == 0) return; for (int i = 0; i < length; ++i) { const int begin = dp[index][i]; if (begin == 0) results.push_back(s.substr(0, index+1)+result); else DFS(results, dp, begin-1, " "+s.substr(begin, index-begin+1)+result, s); } } vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> results; const int length = s.size(); vector<vector<int> > dp(length, vector<int>()); for (int i = 0; i < length; ++i) { if (dict.find(s.substr(0, i+1)) != dict.end()) dp[i].push_back(0); for (int j = 0; j < i; ++j) if (!dp[j].empty() && dict.find(s.substr(j+1, i-j)) != dict.end()) dp[i].push_back(j+1); } DFS(results, dp, length-1, "", s); return results; }};</span>
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
- Word Break II -- LeetCode
- 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
- hdoj.2519 新生晚会 20140724
- 如何使用boost对各个类型进行转化
- 杭电ACM 1001 sum problem
- hdu 1267 下沙的沙子有几粒?
- “逃离朋友圈”能否催生新微信
- LeetCode-Word Break II
- 第三方API的调用开发
- hibernate的简单配置
- 关于Build Active Architecture Only属性
- Android系统启动流程 -- android层
- MongoDB在CentOS 7上的systemctl服务配置
- hdoj.1431 素数回文 20140724
- faac库的编译与移植
- ASCLL码排序