DP + 剪枝

 1 class Solution{
 2     public:
 3     bool wordBreakHelper(string s, unordered_set<string> &dict,unordered_set<string> &unmatch, int maxLength) {
 4         if(s.length() == 0) return true;
 5         
 6         for(int i = 1; i <= maxLength; i++){
 7             
 8             if(dict.find(s.substr(0,i)) != dict.end()){
 9                 
10                 if(unmatch.find(s.substr(i)) != unmatch.end())continue;
11                 else{
12                     if(wordBreakHelper(s.substr(i),dict,unmatch,maxLength)) return true;
13                     else unmatch.insert(s.substr(i));
14                 }
15             }
16         }
17         return false;
18     }
19     bool wordBreak(string s, unordered_set<string> &dict) {
20         
21         if(s.size() == 0) return true;
22         unordered_set<string> unmatch;
23         int maxLength = 0;
24         unordered_set<string> :: iterator it;
25         for (it = dict.begin(); it != dict.end(); it++){
26             if (it->size()>maxLength) maxLength = it->size();
27         }
28         
29         return wordBreakHelper(s,dict,unmatch,maxLength);
30     }
31 };

 

posted on 2013-10-27 02:02  tanghulu321  阅读(160)  评论(0编辑  收藏  举报