- 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:
- []
- Approach #1: Recursive. [C++]
- class Solution {
- private:
- unordered_map<string, vector> m;
- vector combine(string Word, vector prev) {
- for (int i = 0; i <prev.size(); ++i) {
- prev[i] += ' ' + Word;
- }
- return prev;
- }
- public:
- vector wordBreak(string s, vector& wordDict) {
- unordered_set wordDict_(wordDict.begin(), wordDict.end());
- if (m.count(s)) return m[s];
- vector result;
- if (wordDict_.find(s) != wordDict_.end()) {
- result.push_back(s);
- }
- for (int i = 1; i <s.size(); ++i) {
- string Word = s.substr(i);
- if (wordDict_.find(Word) != wordDict_.end()) {
- string rem = s.substr(0, i);
- vector prev = combine(Word, wordBreak(rem, wordDict));
- result.insert(result.end(), prev.begin(), prev.end());
- }
- }
- m[s] = result;
- return result;
- }
- };
来源: http://www.bubuko.com/infodetail-2945147.html