Wednesday, November 13, 2013

Leetcode Problem : Word Break II

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


Code

bool wb_r2(int row,const string& s, unordered_set<string> &dict,vector<string>& result,int pos,vector<string>& ret){
    if(row == 0){
        string tmp;
        for(int i = pos - 1;i >= 0;--i){
            if(i != pos - 1)
                tmp += " ";
            tmp += result[i];
        }
        ret.push_back(tmp);
        return true;
    }
    for(int i = 0;i < row;++i){
        if(dict.find(s.substr(i,row - i)) != dict.end()){
            if(result.size() == pos)
                result.resize(2*pos + 1);
            result[pos] = s.substr(i,row - i);
            wb_r2(i,s,dict,result,pos + 1,ret);
        }
    }
    return false;
}
    
vector<string> wordBreak(string s, unordered_set<string> &dict) {
    // Note: The Solution object is instantiated only once and is reused by each test case.
    vector<string> result;
    vector<string> ret;
    int pos = 0;
    wb_r2(s.size(),s,dict,result,pos,ret);
    return ret;
}

No comments:

Post a Comment