[LeetCode] 140. Word Break II

思路:
这题做出来以后成就感爆棚啊…第一个是我写的一个标准DFS, 但过不去大样本, 会超时. 第二个版本是借助Word Break http://blog.csdn.net/hiimdaosui/article/details/52457700 里面的DP数组做剪枝, 这样就可以过大样本了.

void dfs(vector<string>& res, string& candidate, string& s, unordered_set<string>& wordDict, int start) {
        if (start == s.length()) {
            candidate.pop_back();
            res.push_back(candidate);
            return;
        }
        for (int i = start; i < s.length(); i++) {
            string temp = candidate;
            string cur = s.substr(start, i - start + 1);
            if (wordDict.count(cur)) {
                candidate += cur + " ";
                dfs(res, candidate, s, wordDict, i + 1);
                candidate = temp;
            }
        }
    }

    vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
        vector<string> res;
        string candidate = "";
        dfs(res, candidate, s, wordDict, 0);
        return res;
    }
void dfs(vector<string>& res, string& candidate, string& s, unordered_set<string>& wordDict, int start, bool breakable[]) {
    if (start == s.length()) {
        candidate.pop_back();
        res.push_back(candidate);
        return;
    }
    for (int i = start; i < s.length(); i++) {
        string cur = s.substr(start, i - start + 1);
        if (breakable[i + 1] && wordDict.count(cur)) {
            string temp = candidate;
            candidate += cur + " ";
            dfs(res, candidate, s, wordDict, i + 1, breakable);
            candidate = temp;
        }
    }
}

vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
    int slen = s.length();
    vector<string> res;
    if (! slen) return res;

    bool breakable[slen + 1] = {0};
    breakable[0] = true;

    for (int i = 1; i <= slen; i++) {
        for (int j = 0; j < i; j++) {
            string cur = s.substr(j, i - j);
            if (breakable[j] && wordDict.count(cur)) {
                breakable[i] = true;
                break;
            }
        }
    }

    string candidate = "";
    if (breakable[slen])
        dfs(res, candidate, s, wordDict, 0, breakable);
    return res;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值