[LeetCode-72] Edit Distance

Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)

You have the following 3 operations permitted on a word:

a) Insert a character
b) Delete a character
c) Replace a character

 

DP特训第一弹~某种情况下的最小路径,就是分别增、删、改所产生结果的最小值,中间结果记录即可~

 

 1 class Solution {
 2     public:
 3         int getMinDistance(const string& word1, int let_num1,
 4                 const string& word2, int let_num2,                                  
 5                 int** result_map)                                                  
 6         {                                                                          
 7             if (-1 != result_map[let_num1][let_num2])
 8             {
 9                 return result_map[let_num1][let_num2];                              
10             }
11             int dis_d = getMinDistance(word1, let_num1 - 1, word2, let_num2, result_map) + 1;        
12             int dis_i = getMinDistance(word1, let_num1, word2, let_num2 - 1, result_map) + 1;
13             int dis_r = getMinDistance(word1, let_num1 - 1, word2, let_num2 - 1, result_map) +      
14                 (word1[let_num1 - 1] == word2[let_num2 - 1] ? 0 : 1);
15             result_map[let_num1][let_num2] = min<int>(min<int>(dis_d, dis_i), dis_r);
16             return result_map[let_num1][let_num2];
17         }                                                                          
18         int minDistance(string word1, string word2) {
19             // Start typing your C/C++ solution below                              
20             // DO NOT write int main() function                                    
21             int len1 = word1.length();
22             int len2 = word2.length();
23             int** result = new int* [len1 + 1];                                        
24             for (int i = 0; i <= len1; ++i)                                          
25             {
26                 result[i] = new int [len2 + 1];                                        
27                 result[i][0] = i;
28                 for (int j = 1; j <= len2; ++j)                                      
29                 {                                                                  
30                     result[i][j] = ((0 == i) ? j : -1);                              
31                 }
32             }
33             return getMinDistance(word1, len1, word2, len2, result);                
34         }  
35 };  
View Code

 

posted on 2013-08-21 22:08  似溦若岚  阅读(155)  评论(0编辑  收藏  举报

导航