Word Break II

来源:互联网 发布:我的世界pe苦力防爆js 编辑:程序博客网 时间:2024/04/29 23:13

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

算法思想:其实可以用动态规划,时间复杂度O(n^2),但需要缓存表,空间开销较大,会超空间。既然空间限制很严格那就只能用深搜了。纯深搜必然超时,考虑剪枝。f[i]==true 表示子串s[0,i]是可以分成若干个单词的,g[i][j]==true表示子串s[j][i]就是一个单词。生成f,g后就根据得到的f,g深搜。

class Solution {public:    bool *f,**g;    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {        int n = s.length();        if(n==0) return vector<string>();        f = new bool[n+1];   g = new bool*[n];        for(int i=0;i<n;i++){ g[i] = new bool[n]; memset(g[i],false,n); }        memset(f,false,n+1);               f++; f[-1] = true;        for(int i=0;i<n;i++){            for(int j=i-1;j>=-1;j--){                if(f[j] && wordDict.find(s.substr(j+1,i-j))!=wordDict.end()){                    f[i] = true;                    g[i][j+1] = true;                }            }        }                list<string> path;        vector<string> res;        genPath(s,wordDict,res,path, n-1);        return res;    }        void genPath(const string& s,unordered_set<string>& wordDict,vector<string> &res,list<string> &path, int k)    {        if(k==-1){            string r = "";            for(list<string>::iterator it = path.begin();it!=path.end();){                r.append(*it);                ++it;                if(it!=path.end()) r.append(" ");            }                        res.push_back(r);            return;        }                for(int i=k;i>=0;--i){            if(g[k][i] && f[i-1]){                                path.push_front(s.substr(i,k-i+1));                genPath(s,wordDict,res,path,i-1);                path.pop_front();  //回溯            }        }    }};


0 0
原创粉丝点击