Do not confused with min cut again!!!!!!!!!!!!

 1 class Solution {
 2 public:
 3     bool canBreak(string s, unordered_set<string> &dict) {
 4         int len = s.size();
 5         if (len == 0) return false;
 6         vector<bool> dp(len+1, false);
 7         dp[0] = true;
 8         for (int i = 1; i <= len; i++) {
 9             for (int j = i-1; j >= 0; j--) {
10                 if (dp[j] && dict.find(s.substr(j, i-j)) != dict.end()) {
11                     dp[i] = true;
12                     break;
13                 }
14             }
15         }
16         return dp[len];
17     }
18     void getBreak(vector<string> &result, string s, string current, unordered_set<string> dict, int index) {
19         if (index == s.size()) {
20             result.push_back(current);
21             return;
22         }
23         if (index != 0) current += ' ';
24         for (int i = index; i < s.size(); i++) {
25             if (dict.find(s.substr(index, i - index+1)) != dict.end()) {
26                 getBreak(result, s, current + s.substr(index, i - index+1), dict, i+1);
27             }
28         }
29     }
30     vector<string> wordBreak(string s, unordered_set<string> &dict) {
31         vector<string> result;
32         if (!canBreak(s, dict))  return result;
33         getBreak(result, s, "", dict, 0);
34         return result;
35     }
36 };

 

posted on 2015-03-25 09:11  keepshuatishuati  阅读(116)  评论(0编辑  收藏  举报