File tree 1 file changed +33
-0
lines changed
1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -60,3 +60,36 @@ class Solution {
60
60
return prev[n]
61
61
}
62
62
}
63
+
64
+
65
+ /*
66
+ * DFS/Recursion + memoization Time O(m*n) and space O(n*m)
67
+ */
68
+ class Solution {
69
+ fun minDistance (word1 : String , word2 : String ): Int {
70
+
71
+ val cache = Array (word1.length + 1 ) { IntArray (word2.length + 1 ){ Integer .MAX_VALUE } }
72
+
73
+ fun dfs (i : Int , j : Int ): Int {
74
+ if (i == word1.length && j == word2.length) return 0
75
+ else if (i == word1.length) return word2.length - j
76
+ else if (j == word2.length) return word1.length - i
77
+
78
+ if (cache[i][j] != Integer .MAX_VALUE ) return cache[i][j]
79
+
80
+ if (word1[i] == word2[j]) {
81
+ cache[i][j] = dfs(i + 1 , j + 1 )
82
+ } else {
83
+ cache[i][j] = 1 + minOf(
84
+ dfs(i + 1 , j),
85
+ dfs(i, j + 1 ),
86
+ dfs(i + 1 , j + 1 )
87
+ )
88
+ }
89
+
90
+ return cache[i][j]
91
+ }
92
+
93
+ return dfs(0 , 0 )
94
+ }
95
+ }
You can’t perform that action at this time.
0 commit comments