word-break-ii leetcode C++

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

C++

class Solution {
public:
    vector wordBreak(string s, unordered_set &dict){
        vector result;
        if(dict.find(s)!=dict.end()) 
            result.push_back(s);
        for(int i=1;i left = wordBreak(str,dict);
            Add(left,w);
            result.insert(result.begin(), left.begin(), left.end());
        }         
        return result;
    }
    
    void Add(vector &str, string w){
        for(vector::iterator it=str.begin();it!=str.end();it++)
            *it += " " + w;     
    }
    
    vector wordBreak2(string s, unordered_set &dict){
        vector result;
        if (dict.find(s) != dict.end()) 
            result.push_back(s);
        for(int i = s.size() -1; i > 0;i--){
            string w = s.substr(i);
            if(dict.find(w) == dict.end())
                continue;
            string str = s.substr(0,i);
            vector left = wordBreak(str,dict);
            Add(left,w);
            result.insert(result.end(),left.begin(),left.end());
        }
        return result;
    }
};

 

你可能感兴趣的:(Algorithm,牛客网,C++,算法,leetcode)