力扣算法——140WordBreakIIH
Posted 自由の翼
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了力扣算法——140WordBreakIIH相关的知识,希望对你有一定的参考价值。
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example 1:
Input: s = "catsanddog
" wordDict =["cat", "cats", "and", "sand", "dog"]
Output:[ "cats and dog", "cat sand dog" ]
Example 2:
Input: s = "pineapplepenapple" wordDict = ["apple", "pen", "applepen", "pine", "pineapple"] Output: [ "pine apple pen apple", "pineapple pen apple", "pine applepen apple" ] Explanation: Note that you are allowed to reuse a dictionary word.
Example 3:
Input: s = "catsandog" wordDict = ["cats", "dog", "sand", "and", "cat"] Output: []
Solution:
方法一,使用递归:【通不过牛客的例子】
1 class Solution { 2 public: 3 unordered_map<string, vector<string>>map; 4 vector<string> wordBreak(string s, unordered_set<string> &dict) { 5 if (map.find(s) != map.end())return map[s]; 6 if (s.empty())return { "" }; 7 vector<string>res; 8 for (auto word : dict) 9 { 10 if (s.substr(0, word.size()) != word)continue; 11 vector<string>rem = wordBreak(s.substr(word.size()), dict); 12 for (auto str : rem) 13 res.push_back(word + (str.empty() ? "" : " ") + str); 14 } 15 return map[s] = res; 16 } 17 };
方法二:使用动态规划
1 //使用动态规划 2 3 class Solution { 4 public: 5 vector<string> wordBreak(string s, unordered_set<string> &dict) { 6 int len = s.length(); 7 dp = new vector<bool>[len]; 8 for (int pos = 0; pos < len; pos++) { 9 for (int i = 1; i < len - pos + 1; i++) { 10 if (dict.find(s.substr(pos, i)) != dict.end()) 11 dp[pos].push_back(true); 12 else 13 dp[pos].push_back(false); 14 } 15 } 16 dfs(s, len - 1); 17 return res; 18 } 19 void dfs(string s, int n) { 20 if (n >= 0) { 21 for (int i = n; i >= 0; i--) { 22 if (dp[i][n - i]) { 23 mid.push_back(s.substr(i, n - i + 1)); 24 dfs(s, i - 1); 25 mid.pop_back(); 26 } 27 } 28 } 29 else { 30 string r; 31 for (int j = mid.size() - 1; j >= 0; j--) { 32 r += mid[j]; 33 if (j > 0) 34 r += " "; 35 } 36 res.push_back(r); 37 } 38 } 39 vector<bool> *dp; 40 vector<string> res; 41 vector<string> mid; 42 };
以上是关于力扣算法——140WordBreakIIH的主要内容,如果未能解决你的问题,请参考以下文章
2021-12-24:划分字母区间。 字符串 S 由小写字母组成。我们要把这个字符串划分为尽可能多的片段,同一字母最多出现在一个片段中。返回一个表示每个字符串片段的长度的列表。 力扣763。某大厂面试