[记忆化搜索] 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; } };

 

posted @ 2019-08-08 17:57  fish1996  阅读(153)  评论(0编辑  收藏  举报