• Word Break II -- leetcode


    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.

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

    推断不可分隔也非常easy,即从一个位置起開始递归后。假设结果集没有添加,则该位置不可分隔。


    此代码在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;
        }
    };


  • 相关阅读:
    CSP2019滚粗记
    [总结] wqs二分学习笔记
    [总结] 圆方树学习笔记
    [CF960G] Bandit Blues
    [总结] 第一类斯特林数
    [EOJ629] 两开花
    [CF286E] Ladies' shop
    [总结] 动态DP学习笔记
    [BZOJ3879] SvT
    [总结] 替罪羊树学习笔记
  • 原文地址:https://www.cnblogs.com/zhchoutai/p/7274956.html
Copyright © 2020-2023  润新知