<p>Given two strings <code>word1</code> and <code>word2</code>, return <em>the minimum number of <strong>steps</strong> required to make</em> <code>word1</code> <em>and</em> <code>word2</code> <em>the same</em>.</p>

<p>In one <strong>step</strong>, you can delete exactly one character in either string.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> word1 = &quot;sea&quot;, word2 = &quot;eat&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> You need one step to make &quot;sea&quot; to &quot;ea&quot; and another step to make &quot;eat&quot; to &quot;ea&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> word1 = &quot;leetcode&quot;, word2 = &quot;etco&quot;
<strong>Output:</strong> 4
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= word1.length, word2.length &lt;= 500</code></li>
	<li><code>word1</code> and <code>word2</code> consist of only lowercase English letters.</li>
</ul>

#pragma GCC optimize("Ofast")
static auto _ = [](){std::ios::sync_with_stdio(false); std::cin.tie(nullptr); return nullptr;}();

class Solution1 {
    int dp[501][501];
    int solve(int i, int j, std::string &s, std::string &t) {
        if(i < 0 || j < 0) return 0;
        if(dp[i][j] != -1) return dp[i][j];

        if(s[i] == t[j]) return dp[i][j] = 1 + solve(i - 1, j - 1, s, t);

        int op1 = solve(i - 1, j, s, t);
        int op2 = solve(i, j - 1, s, t);

        return dp[i][j] = std::max(op1, op2);
    }
public:
    int minDistance(std::string word1, std::string word2) {
        int n = word1.length(), m = word2.length();
        memset(dp, -1, sizeof(dp));
        int totalLength = n + m;
        int lcs = solve(n - 1, m - 1, word1, word2);
        return totalLength - (2 * lcs);
    }
};

class Solution {
public:
    int minDistance(std::string s, std::string t) {
        int n = s.length(), m = t.length();
        int N = std::max(n, m);
        int currDp[N + 1], prevDp[N + 1];
        memset(currDp, 0, sizeof(currDp));
        memset(prevDp, 0, sizeof(prevDp));
        for(int i = 1; i <= n; i++) {
            for(int j = 1; j <= m; j++) {
                if(s[i - 1] == t[j - 1]) currDp[j] = 1 + prevDp[j - 1];
                else {
                    currDp[j] = std::max(prevDp[j], currDp[j - 1]);
                }
            }
            memcpy(prevDp, currDp, sizeof(prevDp));
        }
        return (n + m) - (2 * prevDp[m]);
    }
};
12288