leetcode wordbreak

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



这道题如果单纯用回溯法,方法如下:即在对于字符串s,从头开始找字串是否在字典中,如果不在就增加子串长度,如果找到子串,则可以递归往下查找下一个位置的字串。


这么做绝对是可以找到正确答案的,但是却有可能进行重复的搜索,例如上例,最后的单词dog 实际上就是会被重复搜索,为了避免这种重复的搜索,我们可以用一个结构记录下已经搜索过的路径。vv[length]。vv[i]存储着一个队列,队列中表示所有可以通过字串搜索达到位置i的上一个字符串的位置。

例如上例中: vv[3]=0 vv[4]=0 vv[7]=3,4 v[10]=8表示3,4位置通过字串查找可以到达7位置。

构建这么一个表可以防止重复搜索。


第二步利用这个表从后往前构建我们所需要的解。

由vv这个结构,我们先把s[7,10-1]这个字串找到,再结合s[3,7-1] s[4,7-1],最后结合s[0,3-1],s[0,4-1]就能得到结果了。

<pre name="code" class="cpp">class Solution {
public:
      	vector<string> wordBreak(string s, unordered_set<string> &dict) {
   		vector<string>res;
   		
   		
   		if(dict.empty())return res;
   		int length=s.size();
   		vector<vector<int> > vv(length+1);
   		vv[0].push_back(0);
   		for(int i=0;i<length;i++){
   			if(!vv[i].empty()){
   				for(int j=1;j<=length-i;j++){
   					if(dict.count(s.substr(i,j))>0){
   						vv[i+j].push_back(i);
   					}
   				}
   			}
   		}
   		vector<vector<string> > rr(length+1);//从后往前构建字符串
   		rr[length].push_back("");
   		for(int i=length;i>=1;i--){//类似于路径的乘法法则n*m条路径
   			for(int j=0;j<vv[i].size();j++){
   				int index=vv[i][j];
   				for(int k=0;k<rr[i].size();k++){if(i==length){//如果是最后的字符
rr[index].push_back(s.substr(index,i-index));
   					}
   					else{
   						rr[index].push_back(s.substr(index,i-index)+" "+rr[i][k]);
   					}
   				}
   			}
   		}

   		

   		 
   		return rr[0];
    }
 
};


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值