forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
53 lines (38 loc) · 1.21 KB
/
main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/// Source : https://leetcode.com/problems/edit-distance/
/// Author : liuyubobobo
/// Time : 2018-11-23
#include <iostream>
#include <vector>
#include <map>
using namespace std;
/// Memory Serach
/// Time Complexity: O(len(word1) * len(word2))
/// Space Complexity: O(len(word1) * len(word2))
class Solution {
private:
map<pair<int, int>, int> dp;
public:
int minDistance(string word1, string word2) {
return dfs(word1, word2, 0, 0);
}
private:
int dfs(const string& word1, const string& word2, int index1, int index2){
if(index1 == word1.size())
return word2.size() - index2;
if(index2 == word2.size())
return word1.size() - index1;
pair<int, int> hash = make_pair(index1, index2);
if(dp.count(hash))
return dp[hash];
int res = INT_MAX;
if(word1[index1] == word2[index2])
res = min(res, dfs(word1, word2, index1 + 1, index2 + 1));
res = min(res, 1 + dfs(word1, word2, index1, index2 + 1));
res = min(res, 1 + dfs(word1, word2, index1 + 1, index2));
res = min(res, 1 + dfs(word1, word2, index1 + 1, index2 + 1));
return dp[hash] = res;
}
};
int main() {
return 0;
}