LeetCode 140. Word Break II

问题

https://leetcode.com/problems/word-break-ii/

解法

dp , 状态dp[i] = true 表示s.substr(i) 是能被分开. 递推公式为:
dp[i] = dp[i+1] && InDict(s.substr(i, 1)) || dp[i+2] && InDict(s.substr(i, 2)) …
当求出dp[] 数组后, 可以使用dfs 查找所有结果。

class Solution {
public:
    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        bool dp[s.size()+1];
        dp[s.size()] = true;
        for (int i=s.size()-1; i>=0; --i)
        {
            dp[i] = false;
            for (int j = 1; i+j<=s.size(); ++j)
            {
                if (dp[i+j])
                {
                    string now = s.substr(i, j);
                    if (wordDict.find(now)!= wordDict.end())
                    {
                        dp[i] = true;
                        break;
                    }
                }
            }
        }
        vector<string> ret;
        if (dp[0] == false)
            return ret;
        findResult(ret, 0, "", dp, s, wordDict);
        return ret;
    }
private:
    void findResult(vector<string> &ret, int pos, string curResult, bool dp[], string& s, unordered_set<string>& wordDict)
    {
        if (pos == s.size())
        {
            // elimate last space;
            curResult.pop_back();
            ret.push_back(curResult);
            return;
        }

        for (int i=1; i+pos <=s.size(); ++i)
        {
            if (dp[pos+i])
            {
                string now = s.substr(pos, i);
                if (wordDict.find(now) != wordDict.end())
                {
                    findResult(ret, pos+i, curResult + now + " ", dp, s, wordDict);
                }
            }
        }
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值