Word Break II leetcode

79 篇文章 0 订阅

题目链接:http://oj.leetcode.com/problems/word-break-ii/

Word Break II

  Total Accepted: 8462  Total Submissions: 54584 My Submissions

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


看了大神的博客才写出来的。搜索+路径输出,用match[len][i],表示从i开始,长度为len的字符串能否在进行分割,每次搜索时对余下部分进行判断,从而进行剪枝。


code:

class Solution 
{
public:
    vector<string> ans;
    vector<string> had;
    vector<string> wordBreak(string s, unordered_set<string> &dict) 
    {
        int LEN=s.size();
        vector<vector<bool> > match(LEN+1,vector<bool>(LEN+1,false));
        for(int i=0;i<=LEN;i++)
        {
            match[0][i]=true;//从i开始,长度为0的,当然为true了
        }
        for(int len=1;len<=LEN;len++)
        {
            for(int beg=0;beg+len<=LEN;beg++)
            {
                string tmp=s.substr(beg,len);
                if(dict.count(tmp)>0)
                {
                    match[len][beg]=true;
                }
                else//看能不能由以前的状态推出来
                {
                    for(int plen=1;plen<len;plen++)
                    {
                        match[len][beg]=match[len-plen][beg+plen]&match[plen][beg];
                        if(match[len][beg])
                            break;
                    }
                }
            }
        }
        if(match[LEN][0]==false)
        {
            return vector<string> ();
        }
        ans.clear();
        had.clear();
        dfs(s,0,match,dict);
        return ans;
    }
    void dfs(string &s,int k,vector<vector<bool> > &match,unordered_set<string> &dict)
    {
        int LEN=s.size();
        if(k>=LEN)
        {
            if(!had.empty())
            {
                string res;
                for(int i=0;i<had.size();i++)
                {
                    res+=had[i];
                    if(i!=had.size()-1)
                        res+=" ";
                }
                ans.push_back(res);
                return;
            }
        }
        for(int len=1;k+len<=LEN;len++)
        {
            string tmp=s.substr(k,len);
            if(dict.count(tmp)>0&&match[LEN-k-len][k+len])
            {
                had.push_back(tmp);
                dfs(s,k+len,match,dict);
                had.pop_back();
            }
        }
    }
};




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值