[LeetCode] 140、单词拆分Ⅱ

探讨了如何利用字典中的单词对给定字符串进行有效拆分,形成合法句子的所有可能性。介绍了使用回溯算法(DFS)解决此问题的思路与实现过程。

题目描述

给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。

说明:

  • 分隔时可以重复使用字典中的单词。
  • 你可以假设字典中没有重复的单词。

示例:

输入:
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出:
[
  "cats and dog",
  "cat sand dog"
]

解题思路

先做139题。会做139题就行,这个题有点难了,可战略性放弃。只是看着大佬题解,转成C++代码通过了,回溯(dfs)部分并是不很理解。

参考代码

class Solution {
public:
    vector<string> wordBreak(string str, vector<string>& wordDict) {
        int length = str.length();

        unordered_set<string> word_set(wordDict.begin(), wordDict.end());
        bool dp[length];
        memset(dp, 0, sizeof(dp));

        string tmp;   // 必须这么写,uset.count("" + str[0])这么写不可以!
        tmp += str[0];
        if(word_set.count(tmp) > 0)
            dp[0] = true;

        for(int i = 1; i < length; i++){
            if(word_set.count(str.substr(0, i+1)) > 0){
                dp[i] = true;
                continue;
            }

            for(int j = 0; j < i; j++){
                if(dp[j] && word_set.count(str.substr(j+1, i-j)) > 0){
                    dp[i] = true;
                    break;
                }
            }
        }
        
        // 以上是139题的代码,直接套用。
        vector<string> res;
        if(dp[length - 1]){
            deque<string> path;
            dfs(str, length-1, word_set, res, path, dp);
        }
         
        return res;
    }
    
    // 回溯
    void dfs(string &str, int curEnd, unordered_set<string> &word_set, vector<string> &res, deque<string> &path, bool* dp){
        
        string prefix = str.substr(0, curEnd+1);
        if(word_set.count(prefix) > 0){
            path.push_front(prefix);
            
            string tmp = "";
            for(auto s: path)
                tmp += (s + " ");
            tmp = tmp.substr(0, tmp.size() - 1);
            res.push_back(tmp);
            
            path.pop_front();
        }
        
        for(int i = 0; i < curEnd; i++){
            if(dp[i]){
                string suffix = str.substr(i+1, curEnd-i);
                if(word_set.count(suffix) > 0){
                    path.push_front(suffix);
                    dfs(str, i, word_set, res, path, dp);
                    path.pop_front();
                }
            }
            
        }
    }
    
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值