【2.7】回溯算法-解单词拆分 II

一、题目

        给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
        分隔时可以重复使用字典中的单词。
        你可以假设字典中没有重复的单词。

示例 1:
输入 :
s = "catsanddog"
wordDict = ["cat", "cats", "and", "sand", "dog"]
输出 :
[
"cats and dog",
"cat sand dog"
]
示例 2:
输入 :
s = "pineapplepenapple"
wordDict = ["apple", "pen", "applepen", "pine", "pineapple"]
输出 :
[
"pine apple pen apple",
"pineapple pen apple",
"pine applepen apple"
]
解释 : 注意你可以重复使用字典中的单词。
示例 3:
输入 :
s = "catsandog"
wordDict = ["cats", "dog", "sand", "and", "cat"]
输出 :
[ ]

二、解题思路

        今天的题目不仅要求判断字符串是否可以拆分,还需要打印出所有可能的拆分结果。判断字符串是否可拆分相对简单,我们可以直接采用之前提到的动态规划方法来进行判断。如果字符串不能拆分,我们直接返回一个空集合;如果能拆分,我们则进行拆分操作。

        拆分的过程原理相对直观,我们逐步截取字符串的子串,并判断这些子串是否存在于给定的字典中。如果某个子串不在字典中,我们就继续截取更长的子串进行尝试;如果某个子串在字典中,我们就沿着这个子串继续探索下去。如下图所示(图中展示了两种结果,由于空间限制,其余结果用省略号表示未完全展示),我们可以将这个过程看作是一棵n叉树的遍历。通过这种方式,我们可以找到并打印出所有可能的拆分结果。

三、代码实现

#include <iostream>
#include <vector>
#include <string>
#include <unordered_set>
#include <sstream>

using namespace std;

// 字符串加空格拼接
string join(const vector<string>& path) {
    stringstream ss;
    for (size_t i = 0; i < path.size(); ++i) {
        ss << path[i];
        if (i != path.size() - 1) {
            ss << " ";
        }
    }
    return ss.str();
}

// 回溯方式拆解字符串
void traceback(const string& s, const unordered_set<string>& wordDict, int start, vector<string>& res, vector<string>& path) {
    if (start == s.length()) {
        // 如果已经遍历完整个字符串,将当前路径拼接成字符串并添加到结果列表中
        res.push_back(join(path));
        return;
    }
    for (int i = start + 1; i <= s.length(); ++i) {
        string str = s.substr(start, i - start);
        if (wordDict.find(str) == wordDict.end()) {
            // 如果当前子串不在字典中,继续尝试更长的子串
            continue;
        }
        // 如果当前子串在字典中,将其添加到路径中
        path.push_back(str);
        // 递归处理剩余部分
        traceback(s, wordDict, i, res, path);
        // 回溯,移除最后一个添加的子串
        path.pop_back();
    }
}

// 主函数,判断字符串是否可以拆分并打印所有可能的拆分结果
vector<string> wordBreak(const string& s, const vector<string>& wordDict) {
    unordered_set<string> set(wordDict.begin(), wordDict.end());
    int length = s.length();
    vector<bool> dp(length + 1, false);
    dp[0] = true; // 边界条件,空字符串可以被拆分
    for (int i = 1; i <= length; ++i) {
        for (int j = 0; j < i; ++j) {
            // 如果 s[0:j] 可以被拆分且 s[j:i] 在字典中,则 s[0:i] 可以被拆分
            if (dp[j] && set.find(s.substr(j, i - j)) != set.end()) {
                dp[i] = true;
                break;
            }
        }
    }
    vector<string> res;
    if (!dp[length]) {
        // 如果整个字符串不能被拆分,返回空结果
        return res;
    }
    vector<string> path;
    // 如果可以被拆分,使用回溯法找到所有可能的拆分结果
    traceback(s, set, 0, res, path);
    return res;
}

int main() {
    string s = "catsanddog";
    vector<string> wordDict = {"cat", "cats", "and", "sand", "dog"};
    vector<string> result = wordBreak(s, wordDict);
    for (const string& str : result) {
        cout << str << endl;
    }
    return 0;
}

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城狮7号

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值