LeetCode Word Break DP

本文介绍两种解决字符串拆分问题的方法:递归与动态规划。通过递归方式尝试所有可能的子串组合,寻找匹配词典中的单词;使用动态规划优化算法效率,避免重复计算,实现高效拆分。

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

方法一:递归。

Time Limit Exceeded

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        if(s.length() < 1) {
            return true;
        }
        bool flag = false;
        for(int i = 1; i <= s.length(); ++i) {
            string temp = s.substr(0, i);
            unordered_set<string>::iterator it = wordDict.find(temp);
            if(it != wordDict.end()) {
                if(temp.length() == s.length()) {
                    return true;
                }
                flag = wordBreak(s.substr(i), wordDict);
            }
            if(flag) {
                return true;
            }
        }
        return false;
    }
};

方法二:DP。

看Discuss中的思路。经典。
用dp[i]记录原串s[0…i-1]是否可以被切分。dp[0]是说初始情况下认为空串可以被切分。

class Solution {
public:
    bool wordBreak(string s, unordered_set<string>& wordDict) {
        if(wordDict.size() == 0) return false;
        vector<bool> dp(s.size() + 1, false);
        dp[0] = true;

        for(int i = 1; i <= s.size(); ++i) {
            for(int j = i - 1; j >= 0; --j) {
                if(dp[j]) {
                    string temp = s.substr(j, i - j);
                    if(wordDict.find(temp) != wordDict.end()) {
                        dp[i] = true;
                        break;
                    }
                }
            }
        }
        return dp[s.size()];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值