題目:
Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.ui
You have the following 3 operations permitted on a word:spa
- Insert a character
- Delete a character
- Replace a character
Example 1:code
Input: word1 = "horse", word2 = "ros" Output: 3 Explanation: horse -> rorse (replace 'h' with 'r') rorse -> rose (remove 'r') rose -> ros (remove 'e')
Example 2:blog
Input: word1 = "intention", word2 = "execution" Output: 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')
分析:
給定兩個單詞,求word1轉換到word2須要的最少步驟,轉換的操做有三種,分別是插入一個字符,刪除一個字符,替換一個字符。遞歸
d(word1, word2)用來求兩個單詞轉換的須要的最小步數,那麼若是當兩個單詞的最後一個字符是相同的,則d(word1, word2) = d(word1', word2')其word1'和word2'是分別去掉最後一個字符的單詞。rem
若是最後兩個字符不相同時,咱們就須要操做來進行轉換,一種是在word1後增長一個字符,是其最後一個字符和word2的最後一個字符相同,一種是刪去word1的最後一個字符,一種是將word1的最後一個字符轉換成word2的最後一個字符,那麼此時最小的步數就是前三個操做的最小值加上1.string
可能有同窗會問爲何不在word2上進行操做,實際上操做轉換這一步是有5個子問題的,但實際上在word1後增長一個字符和word2最後字符相同,至關於在word2後刪除字符;刪去word1的字符至關於在word2後增長一個字符和word1最後字符相同;而轉換操做明顯是同樣的,因此就合併成爲了三個子問題。it
當遞歸執行到其中一個串爲空串時,則加上另外一個串的長度便可,至關於刪去全部的字符。io
程序:
C++class
class Solution { public: int minDistance(string word1, string word2) { int l1 = word1.length(); int l2 = word2.length(); dp = vector<vector<int>>(l1+1, vector<int>(l2+1, -1)); return minDistance(word1, word2, l1, l2); } private: vector<vector<int>> dp; int minDistance(string& word1, string& word2, int l1, int l2){ if(l1 == 0) return l2; if(l2 == 0) return l1; if(dp[l1][l2] >= 0) return dp[l1][l2]; int res = 0; if(word1[l1-1] == word2[l2-1]){ res = minDistance(word1, word2, l1-1, l2-1); dp[l1][l2] = res; return res; } res = min(minDistance(word1, word2, l1-1, l2), min(minDistance(word1, word2, l1, l2-1), minDistance(word1, word2, l1-1, l2-1))) + 1; dp[l1][l2] = res; return res; } };
Java
class Solution { public int minDistance(String word1, String word2) { int l1 = word1.length(); int l2 = word2.length(); dp = new int[l1+1][l2+1]; for(int i = 0; i < dp.length; ++i){ for(int j = 0; j < dp[i].length; ++j){ dp[i][j] = -1; } } return minDistance(word1, word2, l1, l2); } private int minDistance(String word1, String word2, int l1, int l2){ if(l1 == 0) return l2; if(l2 == 0) return l1; if(dp[l1][l2] >= 0) return dp[l1][l2]; int res = 0; if(word1.charAt(l1-1) == word2.charAt(l2-1)){ res = minDistance(word1, word2, l1-1, l2-1); }else{ res = Math.min(minDistance(word1, word2, l1-1, l2), Math.min(minDistance(word1, word2, l1, l2-1), minDistance(word1, word2, l1-1, l2-1))) + 1; } dp[l1][l2] = res; return res; } private int[][] dp; }