转载

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

解题思想

word-breakii比wordbreak中加了一个要求,必须把中间结果加进来,如果用动态规划

很可能内存超限,用暴力的递归有可能超时

参考 word-breakii

博主采用了一种先找出关键词的方法,在递归的时候就可以省时间

class Solution {  
    vector<string> midres;  
    vector<string> res;  
    vector<bool> *dp;  
public:  
    vector<string> wordBreak(string s, unordered_set<string> &dict) {  
        int len = s.length();  

        dp = new vector<bool>[len];  
        for(int i=0; i<len; ++i){  
            for(int j=i; j<len; ++j){  
                if(dict.find(s.substr(i, j-i+1))!=dict.end()){  
                    dp[i].push_back(true);    
                }else{  
                    dp[i].push_back(false);     
                }  
            }  
        }  
        func(s, len-1);  
        return res;  
    }  

    void func(const string &s, int i){  
        if(i>=0){  
            for(int j=0; j<=i; ++j){  

                if(dp[j][i-j]){

                    midres.push_back(s.substr(j, i-j+1));  
                    func(s, j-1);  
                    midres.pop_back(); 
                }  
            }  
            return;  
        }  
        else{  
            string str;  
            for(int k=midres.size()-1; k>=0; --k){
                str += midres[k];  
                if(k>0)  
                    str += " ";  
            }  
            res.push_back(str);  
            return;  
        }  
    }  
};  
正文到此结束
本文目录