[LeetCode]Word Break II

本文详细介绍了如何使用动态规划和回溯法解决字符串拆分问题,即给定一个字符串和一个字典,如何在字符串中插入空格以构成有效的字典单词,并返回所有可能的组合。

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

在I的基础上要求输出所有解,这样将所有的中间状态保存在prev二维数组中,然后再DFS即可获得所有解。

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string> &dict) {
        vector<bool> dp(s.length() + 1, false);
        dp[0] = true;
        vector<vector<int>> prev(s.length() + 1);
        for (int i = 1; i <= s.length(); i++)
        {
            for (int j = i - 1; j >= 0; j--)
            {
                if (dp[j] && dict.count(s.substr(j, i - j)))
                {
                    dp[i] = true;
                    prev[i].push_back(j);
                }
            }
        }
        vector<string> result;
        searchSolution(result, prev, s, "", s.length());
        return result;
    }
    
    void searchSolution(vector<string> &sol, vector<vector<int>> &prev, string &s, string line, int k)
    {
        if (k == 0)
        {
            if(line.empty()) return;
            line.resize(line.length() - 1); // remove last space character
            sol.push_back(line);
            return;
        }
        for (auto j : prev[k])
            searchSolution(sol, prev, s, s.substr(j, k - j) + " " + line, j);
    }
};
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值