-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEditDistance_72.cpp
80 lines (59 loc) · 2.15 KB
/
EditDistance_72.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/*
~ Author : https://leetcode.com/tridib_2003/
~ Problem : 72. Edit Distance
~ Link : https://leetcode.com/problems/edit-distance/
*/
/* Bottom-Up Approach (Tabulation) */
class Solution {
public:
vector<vector<int> > dp;
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
dp.resize(len1 + 1, vector<int> (len2 + 1));
for (int i = 0; i <= len1; ++i)
dp[i][0] = i;
for (int j = 0; j <= len2; ++j)
dp[0][j] = j;
for (int i = 1; i <= len1; ++i) {
for (int j = 1; j <= len2; ++j) {
int cost = (word1[i - 1] == word2[j - 1]) ? 0 : 1;
dp[i][j] = min(dp[i][j - 1] + 1, min(dp[i - 1][j] + 1,
dp[i - 1][j - 1] + cost));
}
}
return dp[len1][len2];
}
};
// T.C. - O(word1.length() * word2.length())
// S.C. - O(word1.length() * word2.length())
/* Top-Down Approach (Memoization) */
/*
class Solution {
public:
vector<vector<int> > dp;
int minDistanceUtil(int len1, int len2, string word1, string word2) {
if (len1 == 0 && len2 == 0)
return 0;
if (len1 == 0)
return len2;
if (len2 == 0)
return len1;
if (dp[len1][len2] != -1)
return dp[len1][len2];
int cost;
word1[len1 - 1] == word2[len2 - 1] ? cost = 0 : cost = 1;
return dp[len1][len2] = min(minDistanceUtil(len1, len2 - 1, word1, word2) + 1,
min(minDistanceUtil(len1 - 1, len2, word1, word2) + 1,
minDistanceUtil(len1 - 1, len2 - 1, word1, word2) + cost));
}
int minDistance(string word1, string word2) {
int len1 = word1.length();
int len2 = word2.length();
dp.resize(len1 + 1, vector<int> (len2 + 1, -1));
return minDistanceUtil(len1, len2, word1, word2);
}
};
*/
// T.C. - O(word1.length() * word2.length())
// S.C. - O(word1.length() * word2.length())