【leetcode】Word Break II

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

 
与Word Break I类似,只不过需要把所有情况都表示出来。
首先利用Word Break I中的动态规划
 
dp[i]=true 代表了0,1,...,i-1可以用字典中的元素分割
同时新建一个map<int,vector<int>> slice,用于记录分割的位置
如slice[i]=j代表了0,1,...,i-1可以分割为0,1,j-1和j,j+1,...,i-1
 
利用这个slice,利用dfs便可以找到所有的结果
  
 
 1 class Solution {
 2 public:
 3     vector<string> wordBreak(string s, unordered_set<string> &dict) {
 4        
 5  
 6         vector<bool> dp(s.length()+1);
 7         dp[0]=true;
 8         map<int,vector<int> > slice;
 9            
10         // dp[i]  0,1,2...i-1可以被分割
11         // hash[i]=j 表示0,1,2...i-1可以分割为0,1,2,...,j-1和j,j+1,...,i
12         for(int i=1;i<s.length()+1;i++)
13         {
14             for(int j=0;j<i;j++)
15             {
16                 if(dp[j]&&dict.count(s.substr(j,i-j)))
17                 {
18                     dp[i]=true;
19                    
20                     if(slice.find(i)!=slice.end()) slice[i].push_back(j);
21                     else slice[i]=vector<int>(1,j);
22                 }
23             }
24         }
25        
26         vector<string> result;
27        
28         dfs(result,slice,s.length(),s,s);
29         return result;
30     }
31    
32     void dfs(vector<string> &result,map<int,vector<int>> &slice,int start,string &s,string cur)
33     {
34         if(start==0)
35         {
36            cur.erase(0,1);
37            result.push_back(cur);
38            return;
39         }
40        
41         vector<int> sliceV=slice[start];
42         for(int i=0;i<sliceV.size();i++)
43         {
44             string tmp=cur;
45             cur.insert(sliceV[i]," ");
46             dfs(result,slice,sliceV[i],s,cur);
47             cur=tmp;
48         }
49     }
50    
51 };

 

 
posted @ 2015-01-17 21:28  H5开发技术  阅读(165)  评论(0编辑  收藏  举报