Leetcode 140. 单词拆分 II

dfs遍历,用139题的dp来进行剪枝

class Solution {
public:
    vector<bool> dp;
    vector<string> ans, tmp;

    void dfs(string &s, vector<string>& wordDict, int index) {
        if (index == -1) {
            string str;
            auto it = tmp.rbegin();
            str += *it;
            ++it;
            for (; it != tmp.rend(); ++it)
                str += " " + *it;
            ans.push_back(str);
            return;
        }
        for (auto &x : wordDict)
            if (1 + index >= x.size() && (1 + index == x.size() || dp[index - x.size()]) && x == string(s, index + 1 - x.size(), x.size()))
                tmp.push_back(x), dfs(s, wordDict, index - x.size()), tmp.pop_back();
    }
    vector<string> wordBreak(string s, vector<string>& wordDict) {
        dp.assign(s.size(), false);
        for (int i = 0; i < s.size(); ++i) {
            for (auto &x : wordDict)
                if (x.size() <= i + 1 && (i + 1 == x.size() || dp[i - x.size()]) && x == string(s, i + 1 - x.size(), x.size())) {
                    dp[i] = true; break;
                }
        }
        dfs(s, wordDict, s.size() - 1);
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/bendaai/article/details/81007069