1. Recursive Exhaustive Search
Intuition
Recursively evaluate all 3 edit operations at each mismatched character.
Algorithm
- Define
dfs(i, j). - If
i == 0, returnj(must insert j characters). - If
j == 0, returni(must delete i characters). - If
word1[i-1] == word2[j-1], returndfs(i-1, j-1). - Return
1 + min({dfs(i-1, j), dfs(i, j-1), dfs(i-1, j-1)}).
#include <iostream>#include <string>#include <algorithm> using namespace std; int dfs(int i, int j, const string& w1, const string& w2) { if (i == 0) return j; if (j == 0) return i; if (w1[i - 1] == w2[j - 1]) { return dfs(i - 1, j - 1, w1, w2); } int del = dfs(i - 1, j, w1, w2); int ins = dfs(i, j - 1, w1, w2); int rep = dfs(i - 1, j - 1, w1, w2); return 1 + min({del, ins, rep});} int minDistanceRec(string word1, string word2) { return dfs(word1.length(), word2.length(), word1, word2);} int main() { string word1 = "horse", word2 = "ros"; cout << "Edit Distance (Recursive): " << minDistanceRec(word1, word2) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(3^(m + n)) - Space complexity:
O(m + n) call stack