LeetCode-Word Break II

来源:互联网 发布:战龙三国张郺进阶数据 编辑:程序博客网 时间:2024/06/05 03:07

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:

Code:

<span style="font-size:14px;">class Solution {public:    void DFS(vector<string> &results, const vector<vector<int> > &dp, int index, string result, const string &s) {        const int length = dp[index].size();        if (length == 0) return;        for (int i = 0; i < length; ++i) {            const int begin = dp[index][i];            if (begin == 0)                results.push_back(s.substr(0, index+1)+result);            else                DFS(results, dp, begin-1, " "+s.substr(begin, index-begin+1)+result, s);        }    }        vector<string> wordBreak(string s, unordered_set<string> &dict) {        vector<string> results;        const int length = s.size();        vector<vector<int> > dp(length, vector<int>());        for (int i = 0; i < length; ++i) {            if (dict.find(s.substr(0, i+1)) != dict.end())                dp[i].push_back(0);            for (int j = 0; j < i; ++j)                if (!dp[j].empty() && dict.find(s.substr(j+1, i-j)) != dict.end())                    dp[i].push_back(j+1);        }        DFS(results, dp, length-1, "", s);        return results;    }};</span>



0 0
原创粉丝点击