動態規劃——Edit Distance
阿新 • • 發佈:2018-11-01
exe new delete spa ins sta let ati bsp 大意:給定兩個字符串word1和word2,為了使word1變為word2,可以進行增加、刪除、替換字符三種操作,請輸出操作的最少次數
狀態轉移方程: (1)如果word1[i-1] == word2[j-1],則令dp[i][j] = dp[i-1][j-1]
(2)如果word1[i-1] != word2[j-1],由於沒有一個特別有規律的方法來斷定執行何種操作,在增加、刪除、替換三種操作中選一種操作次數少的賦值給dp[i][j];
增加操作:dp[i][j] = dp[i][j-1] + 1
刪除操作:dp[i][j] = dp[i-1][j] + 1 替換操作:dp[i][j] = dp[i-1][j-1] + 1
Example 1:
Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace ‘h‘ with ‘r‘) rorse -> rose (remove ‘r‘) rose -> ros (remove ‘e‘)
Example 2:
Input: word1 = "intention", word2 = "execution" Output:狀態:dp[i][j]把word1[0..i-1]轉換到word2[0..j-1]的最少操作次數5 Explanation: intention -> inention (remove ‘t‘) inention -> enention (replace ‘i‘ with ‘e‘) enention -> exention (replace ‘n‘ with ‘x‘) exention -> exection (replace ‘n‘ with ‘c‘) exection -> execution (insert ‘u‘)
狀態轉移方程: (1)如果word1[i-1] == word2[j-1],則令dp[i][j] = dp[i-1][j-1]
增加操作:dp[i][j] = dp[i][j-1] + 1
刪除操作:dp[i][j] = dp[i-1][j] + 1 替換操作:dp[i][j] = dp[i-1][j-1] + 1
1 int minDistance(string word1,string word2){ 2 int wlen1 = word1.size(); 3 intwlen2 = word2.size(); 4 5 int**dp = new int*[wlen1 + 1]; 6 for (int i = 0; i <= wlen1; i++) 7 dp[i] = new int[wlen2 + 1]; 8 9 //int dp[maxn][maxn] = { 0 }; 10 for (int i = 0; i <= wlen1; i++) 11 dp[i][0] = i; 12 for (int j = 0; j <= wlen2; j++) 13 dp[0][j] = j; 14 int temp = 0; 15 for (int i = 1; i <= wlen1; i++){ 16 for (int j = 1; j <= wlen2; j++){ 17 if (word1[i - 1] == word2[j - 1])dp[i][j] = dp[i - 1][j-1]; 18 else{ 19 temp = dp[i - 1][j - 1]<dp[i - 1][j] ? dp[i - 1][j - 1] : dp[i - 1][j]; 20 temp = temp < dp[i][j - 1] ? temp : dp[i][j - 1]; 21 dp[i][j] = temp + 1; 22 } 23 } 24 } 25 26 /* 27 for (int i = 0; i <= wlen1; i++) 28 delete[]dp[i]; 29 delete[]dp; 30 */ 31 32 return dp[wlen1][wlen2]; 33 }
動態規劃——Edit Distance