[记忆化搜索] leetcode 87 Scramble String

problem:https://leetcode.com/problems/scramble-string/

        记忆化搜索。在所有可能的交换情况中找到合适的。

class Solution {
public:
    unordered_map<string, bool> dp;
    bool isScramble(string s1, string s2) {
        if (dp.find(s1 + " " + s2) != dp.end())
            return dp[s1 + " " + s2];
        int n = s1.size();
        if (s1 == s2)return true;

        vector<int> count(256, 0);
        for (int i = 0; i < s1.size(); i++) {
            count[s1[i]]++;
            count[s2[i]]--;
        }
        for (auto c : count) {
            if (c != 0)return false;
        }
        bool res = false;
        for (int i = 1; i < n; i++) {
            res |= ((isScramble(s1.substr(0, i), s2.substr(n - i)) &&
                isScramble(s2.substr(0, n - i), s1.substr(i))) 
        || (isScramble(s1.substr(0, i), s2.substr(0, i)) && isScramble(s1.substr(i), s2.substr(i)))); } return dp[s1 + " " + s2] = res; } };

猜你喜欢

转载自www.cnblogs.com/fish1996/p/11322753.html