Word Break II -- leetcode

来源:互联网 发布:java基础教程 pdf 编辑:程序博客网 时间:2024/06/04 08:08

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

基本思路:

深度递归(暴力偿试法)

再结合剪枝操作。

剪枝操作思路为:

使用一个数组:breakable[i],  表示从第 i个字符向后直至结束,是否可分解为句子。初始皆为true.

当发现从一个位置不可分隔成数组,则置上标志,以避免后续的重复偿试。

判断不可分隔也很简单,即从一个位置起开始递归后,如果结果集没有增加,则该位置不可分隔。


此代码在leetcode上实际执行时间为4ms。


class Solution {public:    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {        vector<string> ans;        vector<int> breakable(s.size()+1, true);        dfs(ans, s, wordDict, "", 0, breakable);        return ans;    }        void dfs(vector<string> &ans, const string &s, const unordered_set<string> &wordDict,         string sentence, int start, vector<int> &breakable) {        if (start == s.size()) {            ans.push_back(sentence);            return;        }                if (!sentence.empty())            sentence.push_back(' ');                const int old_size = ans.size();        for (int i=start+1; i<=s.size(); i++) {            if (!breakable[i])                continue;            const string word(s.substr(start, i-start));            if (wordDict.find(word) != wordDict.end()) {                dfs(ans, s, wordDict, sentence + word, i, breakable);            }        }        if (old_size == ans.size())            breakable[start] = false;    }};


0 0