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

    Solution: check before constructing the sentences.

     1 class Solution {
     2 public:
     3     vector<string> wordBreak(string s, unordered_set<string> &dict) {
     4         vector<string> res;
     5         if (!wordBreakPossible(s, dict)) return res; //! not pass if ignoring here
     6         wordBreakRe(s, dict, 0, "", res);
     7         return res;
     8     }
     9     
    10     void wordBreakRe(const string &s, const unordered_set<string> &dict, 
    11                      int start, string sentence, vector<string> &res) {
    12         if (start == s.size()) {
    13             res.push_back(sentence);
    14             return;
    15         }
    16         if (start != 0) sentence.push_back(' ');
    17         for (int i = start; i < s.size(); ++i) {
    18             string word = s.substr(start, i-start+1);
    19             if (dict.find(word) == dict.end())
    20                 continue;
    21             wordBreakRe(s, dict, i+1, sentence + word, res);
    22         }
    23     }
    24     
    25     bool wordBreakPossible(const string &s, const unordered_set<string> &dict) {
    26         int N = s.size();
    27         bool canBreak[N+1];
    28         memset(canBreak, false, sizeof(canBreak));
    29         canBreak[0] = true;
    30         for (int i = 1; i <= N; ++i) {
    31             for (int j = i-1; j >= 0; --j) {
    32                 if (canBreak[j] && dict.find(s.substr(j, i-j)) != dict.end()) {
    33                     canBreak[i] = true;
    34                     break;
    35                 }
    36             }
    37         }
    38         return canBreak[N];
    39     }
    40 };
  • 相关阅读:
    codevs 3641 上帝选人
    codevs 1966 乘法游戏
    codevs 1345 饥饿的奶牛
    codevs 1962 马棚问题--序列型DP
    codevs 1959 拔河比赛--判断背包内刚好装满n/2个物品
    codevs 1297 硬币
    [转载]矩阵取数游戏
    101.金明的预算方案(分组背包)
    105.(并查集结合绝对值最小的01背包)选学霸
    POJ 2528 Mayor's posters(线段树)
  • 原文地址:https://www.cnblogs.com/zhengjiankang/p/3659901.html
Copyright © 2020-2023  润新知