Word Break II

本文介绍了一种使用深度优先搜索(DFS)结合剪枝策略来解决单词拆分问题的方法,给定一个字符串和一个词典,目标是将字符串拆分成词典中存在的单词,并返回所有可能的拆分组合。

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

DFS+剪枝

是前面那拆分词语的扩展,除了要判断能否由字典里的词语组成,还要求出所有的组合。

单纯的DFS会TLE,需要剪枝。

class Solution{
private:
    void helper(string& s,unordered_set<string>& wordDict,int start,vector<bool>& possible,string path,vector<string>& res){
        if(start == int(s.length())){
            res.push_back(path);
            return;
        }
        for(int i = start;i<int(s.length());i++){
            string word = s.substr(start,i-start+1);
            if(wordDict.find(word) != wordDict.end() && possible[i+1]){
                if(start == 0)
                    path.append(word);
                else{
                    path.append(" ");
                    path.append(word);
                }
                int oldsize = res.size();
                helper(s,wordDict,i+1,possible,path,res);
                if(int(res.size()) == oldsize) possible[i+1] = false;
                if(start == 0)
                    path.resize(path.size() - word.size());
                else
                    path.resize(path.size() - word.size()-1);
            }
        }
    }
public:
    vector<string> wordBreak(string s,unordered_set<string>& wordDict){
        vector<string> res;
        vector<bool> possible(s.size()+1,true);
        helper(s,wordDict,0,possible,"",res);
        return res;
    }
};

 

 

转载于:https://www.cnblogs.com/wxquare/p/6171483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值