leetcode 140: Word Break II

本文详细介绍了如何使用动态规划和深度优先搜索算法来解决遍历所有路径的问题,避免了仅使用深度优先搜索导致的时间限制错误(TLE)。通过实例演示和代码实现,深入探讨了算法的优化策略。

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

Use DP + DFS to go through all paths. Only DFS will result in TLE.

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        int len=s.length();
        vector<bool> dp(len,0);
        unordered_map<string,vector<string> > children;
        for(int i=0;i<len;i++)
        {
            string temp=s.substr(0,i+1);
            if(wordDict.find(temp)!=wordDict.end())
                dp[i]=1;
            else
            {
                for(int j=0;j<i;j++)
                {
                    if(dp[j]&&wordDict.find(s.substr(j+1,i-j))!=wordDict.end())
                    {
                        dp[i]=1;
                        break;
                    }
                }
            }
        }
        vector<string> res;
        vector<string> path;
        dfs(s,wordDict,dp,res,path);
        return res;
    }
    void dfs(string s,unordered_set<string>& wordDict,vector<bool>& dp,vector<string>& res,vector<string>& path)
    {
        for(int i=s.length()-2;i>=0;i--)
        {
            if(dp[i]&&wordDict.find(s.substr(i+1))!=wordDict.end())
            {
                path.push_back(s.substr(i+1));
                dfs(s.substr(0,i+1),wordDict,dp,res,path);
                path.pop_back();
            }
        }
        if(wordDict.find(s)!=wordDict.end())
        {
            string temp;
            if(path.size()==0)
                temp=s;
            else
            {
                temp=s;
                for(int i=path.size()-1;i>=0;i--)
                    temp+=' '+path[i];
            }
            res.push_back(temp);
        }
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值