lc 140.hard单词拆分II【①动态规划->lc139.单词拆分;②*****枚举 - 回溯法】

博客提供了LeetCode上单词拆分II题目的官方题解链接,还提到了抄答案相关内容,主要围绕该算法题的解答资源。

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

官方题解https://leetcode-cn.com/problems/word-break-ii/solution/dan-ci-chai-fen-ii-by-leetcode-solution/

抄答案:

class Solution {
public:
    unordered_set<string> wordDictSet;
    unordered_map<int, vector<string>> sen;  //记录每个下标对应的字符 以它开头形成的句子的集合

    vector<string> wordBreak(string s, vector<string>& wordDict) {
        wordDictSet=unordered_set(wordDict.begin(),wordDict.end());
        backtrack(s,0);
        return sen[0];
    }

    void backtrack(string &s, int idx){
        if(!sen.count(idx)){  //如果这个下标对应的字符 没有以它开头形成的句子
            if(idx==s.size()){
                sen[idx]={""};  //如果idx指向s末尾,则idx对应的句子集合为一个空字符串(以s[idx]开头的句子为空字符串)
                return;
            }
            sen[idx]={};  //对于非末尾的下标,往后看,看以s[idx]开头能形成哪些句子
            for(int i=idx+1; i<=s.size(); ++i){
                string word=s.substr(idx, i-idx);  //取idx~i子串word
                if(wordDictSet.count(word)){
                    backtrack(s,i);  //如果子串word形成了单词,就在此基础上递归
                    for(string& t:sen[i]){  //修改以s[i]开头的句子集合
                        if(t.empty()) sen[idx].push_back(word);  //如果句子为空,把“word”加入句子集合
                        else sen[idx].push_back(word+" "+t);  //如果句子不为空,把“t word”加入句子集合
                    }
                }
            }
        }
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值