leetcode Word Break II

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        //若i-j之间的字符串为字典某一单词 则令矩阵a[i][j]=1,获得可达图 进行深度优先搜索即可。
		vector<string> vs;
		bool a[1000][1000]={{0}};
		bool dp[1000] = {false};
		dp[0]=true;
		int i;
		int l = s.length();
        for(i=0;i<l;i++){
			if(dp[i]){
                for(int len=1;i+len-1<l;len++){
			    	if(wordDict.count(s.substr(i,len))>0){ 
			    	    dp[i+len]=true;
			    	    a[i][i+len-1]=true;
			    	}   
                }
			}
        }
        if(!dp[l]) return vs;//若dp[l]无法被分割 返回空向量
        else {   //否则进行深度遍历
            string tmp="";
			DFS(tmp,a,0,l,vs,s);
			/*for(int i=0;i<vs.size();i++){
				cout<<vs[i]<<endl;
			}*/
        }
        return vs;
    }

	void DFS(string s,bool a[][1000],int n,int l ,vector<string> &vs1,string s1){//传参时 应注意传入向量的引用 否则只是对副本进行修改
   
		for(int i=n;i<l;i++){
           if(a[n][i]==true){
			   string copy;
			   if(n!=0){
				   copy = s+" "+s1.substr(n,i-n+1);}
			   else{
				   copy = s1.substr(n,i-n+1);
			   }
			   DFS(copy,a,i+1,l,vs1,s1);
			   if(i==l-1){vs1.push_back(copy);break;}
		  
		   }
       }
    }
};

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值