Leetcode--Word Break II

Problem Description:

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题目的经验,这个题目不能直接用DFS来解决,不然肯定会超时,因此先用DP将字符串从右到左依次算出i到n的子串是否能被拆分的flag数组,然后利用DFS利用这个flag数组将所有可能的拆分记录下来,提高了效率。

代码如下:

class Solution {
public:
    
    void dfs(string &s, int begin, int len, unordered_set<string> &dict, 
    vector<bool> &flag, string &str, vector<string> &res)
    {
        if(begin==len)
        {
            res.push_back(str.substr(1));
            return;
        }
        
        for(int i=begin;i<len;++i)
        {
            string substring=s.substr(begin,i-begin+1);
            if(dict.count(substring)==1&&flag[i+1])
            {
                str+=" "+substring;
                dfs(s,i+1,len,dict,flag,str,res);
                str.resize(str.size()-substring.size()-1);
            }
        }
        
    }
    
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<string> res;
        string str;
        if(s.size()==0)
            return res;
        int len=s.size();
        vector<bool> flag(len+1,false);
        flag[len]=true;
        
        for(int i=len-1;i>=0;--i)
            for(int j=len;j>i;--j)
            {
                if(flag[j]&&dict.count(s.substr(i,j-i))==1)
                {
                    flag[i]=true;
                    break;
                }
            }
            
        dfs(s,0,len,dict,flag,str,res);
        return res;

    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值