Word Break II

来源:互联网 发布:linux系统网络配置文件 编辑:程序博客网 时间:2024/05/23 01:21
------QUESTION------

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"].

------SOLUTION------

class Solution {public:    vector<string> wordBreak(string s, unordered_set<string> &dict) {        results.clear();        if(s.size() < 1 || dict.empty()) return results;                 string tmp;        vector<vector<bool>> dp(s.length(),vector<bool>(s.length()+1, false)); //string, started from i, with length j, can be found at least one form in the dict           for (int len = 1; len <= s.length(); len++) {             for (int i = 0; i < s.length() - len + 1; i++) {                 tmp = s.substr(i, len);                 if (dict.find(tmp)!=dict.end()) {                     dp[i][len] = true;                     continue;                 }                 for (int k = 1; k < len; k++) {                     if (dp[i][k] && dp[i + k][len - k]) {                         dp[i][len] = true;                         break;                     }                 }             }         }         if (!dp[0][s.length()]) {             return results;         }                string pre = "";        dfs(s,pre, dp, dict, 0);        return results;    }    void dfs(string &s, string pre, vector<vector<bool>> &dp, unordered_set<string> &dict, int start)    {        if(start == s.length())        {            results.push_back(pre);            return;        }        string backup = pre;        string tmp;        for(int i = 1; i <= s.length()-start;i++)        {            if(!dp[start][i]) continue;            tmp = s.substr(start, i);            if (dict.find(tmp)==dict.end()) continue;            if(pre=="") pre += tmp;            else pre = pre + " " + tmp;            dfs(s, pre, dp, dict, start+i);            pre = backup;        }    }private:     vector<string> results;};


0 0