首页 > 代码库 > Interleaving String [leetcode] DP

Interleaving String [leetcode] DP

dp[k1][k2]:s1[0...k1-1]和s2[0...k2-1]能否合成s3[0...k1 + k2 - 1]

    bool isInterleave(string s1, string s2, string s3) {
        if (s3.size() != s1.size() + s2.size()) return false;
        vector<vector<bool>> dp(s1.size() + 1);
        for (int i = 0; i < dp.size(); i++)
            dp[i] = vector<bool>(s2.size() + 1);
        dp[0][0] = true;//s1[0...k1-1]和s2[0...k2-1]能否合成s3[0...k1 + k2 - 1]
        for (int k1 = 0; k1 <= s1.size(); k1++)
        {
            for (int k2 = 0; k2 <= s2.size(); k2++)
            {
                if (k1 > 0)
                    dp[k1][k2] = dp[k1][k2] || (dp[k1 - 1][k2] && s1[k1 - 1] == s3[k1 + k2 - 1]);
                if (k2 > 0)
                    dp[k1][k2] = dp[k1][k2] || (dp[k1][k2 - 1] && s2[k2 - 1] == s3[k1 + k2 - 1]);
            }
        }
        return dp[s1.size()][s2.size()];
    }


Interleaving String [leetcode] DP