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

class Solution {
public:
    bool dfs(string s,int start,  vector<string>& result, vector<string>& path,  unordered_set<string>& wordDict ,unordered_set <int> & unmatch)
	{
		if(start==s.size())
    	{
    	    string tmp;
    	    for(auto word : path )
    	    {
    	        tmp+=word;
    	        tmp+=" ";
    	    }
            result.push_back(tmp.substr(0,tmp.size()-1));
            return true;
    	}
	    bool ret=false;
     	for(int i=start; i<s.size(); i++)
		{
			string tmp = s.substr(start,i-start+1);
			//如果在i的位置分割过,不匹配,那就不要处理,直接跳过在后面的位置判断
			if(wordDict.count(tmp)>0 && unmatch.count(i)==0 )
			{
	            path.push_back(tmp);
				bool subRet=dfs(s,i+1, result, path, wordDict, unmatch);
			    path.pop_back();
			    if(subRet==false)
	                   unmatch.insert(i);//记录下i的位置,在这里分割过了,没有匹配的,以后就不要再在这里分割了
                else
                    ret=true;//为了告诉上一层,start 与start-1之间分开时可以匹配的
			}
		}
		return ret;
	}
    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
	    unordered_set<int> unmatch;
        vector<string> path;
        vector<string> ret;
         dfs(s, 0, ret, path, wordDict, unmatch);
        return ret;
    	}
};
相关: word break I

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值