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

这题不能直接DFS,否则会超时,联想到上一题,可以跟上题一样先动态规划,判断能否被break,如果s不能被break,那么也没有DFS的必要了,另外在DFS时也可以再利用dp所存的信息从而可以大大得剪掉不必要的操作。

 1 class Solution {
 2 public:
 3     void breakWord(vector<string> &res, string &s, unordered_set<string> &dict, string str, int idx, vector<bool> &dp) {
 4         string substr;
 5         for (int len = 1; idx + len < s.length() + 1; ++len) {
 6             if (dp[idx + len] && dict.count(s.substr(idx,len)) > 0) {
 7                 substr = s.substr(idx, len);
 8                 if (idx + len < s.length()) {
 9                     breakWord(res, s, dict, str + substr + " ", idx + len, dp);
10                 } else {
11                     res.push_back(str + substr);
12                     return;
13                 }
14             }
15         }
16     }
17     
18     vector<string> wordBreak(string s, unordered_set<string> &dict) {
19         vector<bool> dp(s.length() + 1, false);
20         dp[0] = true;
21         for (int i = 0; i < s.length(); ++i) {
22             if (dp[i]) {
23                 for (int len = 1; i + len < s.length() + 1; ++len) {
24                     if (dict.count(s.substr(i, len)) > 0) {
25                         dp[i + len] = true;
26                     }
27                 }
28             }
29         }
30         vector<string> res;
31         if (dp[s.length()]) 
32             breakWord(res, s, dict, "", 0, dp);
33         return res;
34     }
35 };

 

posted @ 2014-04-22 17:16  Eason Liu  阅读(3101)  评论(0编辑  收藏  举报