leetcode 日经贴,Cpp code -Word Break II

来源:互联网 发布:中国社会统计数据库 编辑:程序博客网 时间:2024/05/18 02:04

Word Break II

class Solution {public:    void genvs(const string &s, const vector<vector<int> > &dp, int p, string cs, vector<string> &vs, const vector<int> &valid) {        int n = s.length();        if (p == n) {            vs.push_back(cs);            return ;        }        string delimiter = p == 0? "":" ";        for (int i = p; i < n; ++i) {            if (dp[p][i] && valid[i + 1]) {                genvs(s, dp, i + 1, cs + delimiter + s.substr(p, i  - p + 1), vs, valid);            }        }    }    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {        int n = s.length();        vector<vector<int> > dp;        dp.resize(n);        for (int i = 0; i < n; ++i) {            dp[i].resize(n);        }        //init dp matrix        for (int i = 0; i < n; ++i) {            for (int j = i; j < n; ++j) {                string subs = s.substr(i, j - i + 1);                if (wordDict.find(subs) != wordDict.end()) {                    dp[i][j] = 1;                }            }        }        vector<int> valid(n + 1);        valid[n] = 1;        for (int i = n - 1; i >= 0; --i) {            if (valid[i + 1]) {                for (int j = 0; j <= i; ++j) {                    if (dp[j][i]) {                        valid[j] = 1;                    }                }            }        }        vector<string> ans;        genvs(s, dp, 0, "", ans, valid);        return ans;    }};


0 0