[leetcode]140. Word Break II

链接:https://leetcode.com/problems/word-break-ii/description/


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:
[]

class Solution {
public:
    vector<string> wordBreak(string s, vector<string>& wordDict) 
    {
        unordered_set<string> dict(wordDict.begin(),wordDict.end());        
        vector<bool> possible(s.size()+1, true);
        vector<string> ans;
        string item;
        dfs(s,dict,0,possible, ans, item);
        return ans;
        
    }
    
    bool dfs(string&s, unordered_set<string>& dict, int idx,vector<bool>&possible, vector<string>& ans,string& item )
    {
        bool res = false;
        if(idx==s.size())
        {
           
            ans.push_back(item.substr(0, item.size()-1));
            return true;
        }
        for (int i = idx; i<s.size(); ++i) 
        {
            string word = s.substr(idx, i - idx + 1);

		    if (dict.find(word) != dict.end() && possible[i + 1])
            {
			    item += (word + " ");
			    if (dfs(s, dict, i + 1, possible, ans, item)) 
                    res = true;
			    else 
                    possible[i + 1] = false;
                item.resize(item.size() - word.size() - 1);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocong1990/article/details/80568111