140. Word Break II 分词 DP

本文介绍了一种基于深度优先搜索(DFS)的算法,用于将给定字符串通过字典中的单词进行拆分,并返回所有可能的句子组合。该算法首先使用动态规划(DP)确定有效的单词边界,然后递归地构建所有可能的合法句子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


1.我的解答

参考word break1 dp 
前面是判断dp[i] = (dp[j]==true && s(j...i) in dict)
现在是对于每个位置,用vector记录前面可以割的位置
然后用dfs找出这些word并连接起来


class Solution {
public:
    void dfs(string s, vector<vector<int>>num, int begin, vector<string>& res, string str){
        if(begin == s.size()){
            res.push_back(str);
            return;
        }
        
        for(int i = 0; i < num[begin].size(); i++){
            int end = num[begin][i];
            string temp = s.substr(begin, end-begin);
            string strs = str;
            strs += temp;
            if(end < s.size()) strs += " ";
            dfs(s, num, end, res, strs);
        }
    }

    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        int n = s.size();
        vector<vector<int>>num(n+1,vector<int>());
        num[n].push_back(n);
        for(int i = n-1; i >= 0; i--){
            for(int j = i+1; j <= n; j++){
                if(num[j].size() == 0) continue; //有位置存入,相当于true;没有位置存入,相当于false,直接跳过,体现DP
                string str = s.substr(i, j-i);
                if(wordDict.find(str) != wordDict.end()){
                    num[i].push_back(j);
                }
            }
        }
        vector<string>res;
        string str;
        dfs(s, num, 0, res,str);
        return res;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值