• [LeetCode] Word Break II


    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:

    递归过程注意用空间换时间,以免TLE。

    class Solution {
    public:
        vector<string>* res;
    int* visited;
    string srcStr;
    
    vector<string> word_break(int start, string s, unordered_set<string> &dict)
    {
            if(visited[start] == 1)
                return res[start];
    
            vector<string> ans;
    
            int len = s.length();
            if(len == 0) 
            {
                visited[start] = 1;
                res[start] = ans;
                return ans;
            }
            //enumerate the first space location
            for(int i = 1;i <= len;i++)
            {
                //i is the number of char in the first string
                string firstStr = s.substr(0, i);
                string secondStr = s.substr(i, len - i);
    
                if(dict.find(firstStr) != dict.end())
                {
                    //first string can be found, get the break result of the second string
                    vector<string> secondRes = word_break(start + i, secondStr, dict);
                    
                    if(i == len)
                    {
                        ans.push_back(firstStr);
                    }
                    else
                    {
                        if(secondRes.size() != 0)
                        {
                            for(int j = 0;j < secondRes.size();j++)
                            {
                                string cur = firstStr + " " + secondRes[j];
                            //    cout << "cur = " <<  cur << endl;
                                ans.push_back(cur);
                            }
                        }
                    }
                }
            }    
    
            res[start] = ans;
            visited[start] = 1;
            return ans;
    }
    
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
            srcStr = s;
            vector<string> ans;
            if(s.length() == 0) return ans;
            res = new vector<string>[s.length() + 1];
            visited = new int[s.length() + 1];
            memset(visited, 0, (s.length() + 1) * sizeof(int));
    
            ans = word_break(0, s, dict);
    
            return ans;
        }
    
    };
    View Code
  • 相关阅读:
    安全系列之二:OAuth2.0 开放授权协议
    安全系列之一:忘记密码
    Tomcat剖析(五):Tomcat 容器
    如何做好项目?
    SonarLint(Sonar) 代码质量管理
    一个JavaWeb项目开发总结
    Tomcat剖析(四):Tomcat默认连接器(2)
    Tomcat剖析(四):Tomcat默认连接器(1)
    Spring mvc 字节流
    spring mvc 之初体验
  • 原文地址:https://www.cnblogs.com/changchengxiao/p/3826353.html
Copyright © 2020-2023  润新知