-
-
Notifications
You must be signed in to change notification settings - Fork 110
/
Copy path72._Edit_Distance.cpp
99 lines (83 loc) · 2.39 KB
/
72._Edit_Distance.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// Problem Link
// https://leetcode.com/problems/edit-distance/
// Recursion based approach
class Solution {
public:
int editDis(string& word1, string& word2, int n1, int n2)
{
if(n1 == 0)
return n2;
if(n2 == 0)
return n1;
if(word1[n1-1] == word2[n2-1]) {
return editDis(word1, word2, n1-1, n2-1);
}
return 1+min(editDis(word1, word2, n1, n2-1),
min(editDis(word1, word2, n1-1, n2),
editDis(word1, word2, n1-1, n2-1)));
}
int minDistance(string word1, string word2) {
int n1 = word1.size();
int n2 = word2.size();
return editDis(word1, word2, n1, n2);
}
};
// DP tabulation based approach
class Solution {
public:
int minDistance(string word1, string word2) {
int n=word1.length();
int m=word2.length();
vector<vector<int>> dp(n+1,vector<int>(m+1,0));
for(int i=0;i<=m;++i)
dp[0][i]=i;
for(int i=0;i<=n;++i)
dp[i][0]=i;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=1+min({dp[i-1][j],dp[i-1][j-1],dp[i][j-1]});
}
}
return dp[n][m];
}
};
// DP memoization based approach
class Solution {
public:
int dp[1001][1001];
int editDis(string& word1, string& word2, int n1, int n2)
{
if(n1 == 0)
return n2;
if(n2 == 0)
return n1;
if(dp[n1][n2] !=-1)
{
return dp[n1][n2];
}
if(word1[n1-1] == word2[n2-1]) {
dp[n1][n2] = editDis(word1, word2, n1-1, n2-1);
return dp[n1][n2];
}
dp[n1][n2]= 1+min(editDis(word1, word2, n1, n2-1),
min(editDis(word1, word2, n1-1, n2),
editDis(word1, word2, n1-1, n2-1)));
return dp[n1][n2];
}
int minDistance(string word1, string word2) {
int n1 = word1.size();
int n2 = word2.size();
for(int i=0;i<=n1+1;i++)
{
for(int j=0;j<=n2+1;j++)
{
dp[i][j] = -1;
}
}
dp[n1][n2] = editDis(word1, word2, n1, n2);
return dp[n1][n2];
}
};