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

    动归

    class Solution {
    public:
        void sub(vector<vector<int> >& str,string& s,int index,string& one, vector<string>& ret){
            if(index==0){
                ret.push_back(one);
            }
            else{
                int length=one.length();
                for(int i=0;i<str[index].size();i++){
                    if(index==s.length()){
                        one=s.substr(str[index][i],index-str[index][i])+one;
                    }
                    else{
                        one=s.substr(str[index][i],index-str[index][i])+" "+one;
                    }
                    sub(str,s,str[index][i],one,ret);
                    one=one.substr(one.length()-length,length);
                }
            }
        }
        vector<string> wordBreak(string s, unordered_set<string> &dict) {
            int maxLen=0;
            for(unordered_set<string>::iterator it=dict.begin();it!=dict.end();it++){
                if( (*it).length()>maxLen)maxLen=(*it).length();
            }
            string tmp;
            vector<vector<int> >str;
            vector<bool>acc;
            acc.resize(s.length()+1,false);
            str.resize(s.length()+1);
            acc[0]=true;
            int i=0;
            if(acc[i]){
                int top=min(maxLen,(int)s.length()-i);
                for(int j=1;j<=top;j++){
                    tmp=s.substr(i,j);
                    if(dict.find(tmp)!=dict.end()){
                        acc[i+j]=true;
                        str[i+j].push_back(0);
                    }
                }
            }
            for(int i=1;i<s.length();i++){
                if(acc[i]){
                    int top=min(maxLen,(int)s.length()-i);
                    for(int j=1;j<=top;j++){
                        tmp=s.substr(i,j);
                        if(dict.find(tmp)!=dict.end()){
                            acc[i+j]=true;
                            str[i+j].push_back(i);
                        }
                    }
                }
            }
            string one="";
            vector<string> ret;
            sub(str,s,s.length(),one,ret);
            return ret;
        }
    };
    跟上一题相同策略
  • 相关阅读:
    nginx 添加模块
    zabbix监控nginx status页面
    查看crontab执行记录
    mysql常见问题处理
    iftop简单使用
    TCP的状态及变迁
    CF1174F
    luoguP6326 Shopping
    【THUWC2020】工资分配
    CF1336简要题解
  • 原文地址:https://www.cnblogs.com/superzrx/p/3354813.html
Copyright © 2020-2023  润新知