[LeetCode] Word Break II

来源:互联网 发布:人工智能的前景 编辑:程序博客网 时间:2024/05/29 14:21

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

class Solution {public:    vector<string> wordBreak(string s, unordered_set<string> &dict) {        int len = s.size();        vector<vector<bool>> flag(len, vector<bool>(len, false));        for(int i = 0; i < len; i++)        {            for(int j = 0; j < len; j++)            {                if(dict.find(s.substr(i,j-i+1)) != dict.end())                    flag[i][j] = true;            }        }        vector<string> result;        for(int i = len-1; i >= 0; i--)        {            if(flag[i][len-1])            {                string str = s.substr(i, len-i);                back(flag, i-1, s, str, result);            }        }        return result;    }    void back(vector<vector<bool>> &flag, const int &i, const string &s, string str, vector<string> &result)    {        if(i==-1)        {            result.push_back(str);            return;        }        for(int j = 0; j <= i; j++)        {            if(flag[j][i])            {                string cur_str = s.substr(j, i-j+1) + " " + str;                back(flag, j-1, s, cur_str, result);            }        }    }};



0 0
原创粉丝点击