https://oj.leetcode.com/problems/edit-distance/
动态规划,它的小规模问题是:当 word1 word2都比较小的时候,word1变成 word2需要的变化数。
设数组 record[i][j] 表示word1 从0到 i ,word2 从 0 到 j 的 word1 到 word2 需要经过几次变化。
列等式如下:
record[i][j] = record[i-1][j-1] if 'i'=='j'
record[i][j] = record[i-1][j-1] +1 replace if 'i'!='j'
record[i][j-1] +1 delete
record[i-1][j] +1 insert
取它们3个的最小值。
初始化: record[0][j] = j
record[i][0] = i
class Solution { public: int minDistance(string word1, string word2) { //word1 is smaller if(word1.size()>word2.size()) { string temp; temp = word1; word1 = word2; word2 = temp; } if(word1.empty()) return word2.size(); if(word1 == word2) return 0; //find the max same bits int maxSame = sameBits(word1,word2); return maxSame; } int sameBits(string &word1,string &word2) { vector<vector<int> > record; record.resize(word1.size()+1); for(int i = 0; i<= word1.size();i++) record[i].resize(word2.size()+1); for(int i = 0;i<=word1.size();i++) record[i][0] = i; for(int j = 0;j<=word2.size();j++) record[0][j] = j; for(int row = 1;row<= word1.size();row++) for(int col = 1;col<=word2.size();col++) { if(word1[row-1] == word2[col-1]) record[row][col] = record[row-1][col-1]; else { int _min = min(record[row-1][col],record[row][col-1]); record[row][col] = min(_min,record[row-1][col-1]) + 1; } } return record[word1.size()][word2.size()]; } }; int main() { class Solution mys; string str1 = "distance"; string str2 = "springbok"; cout<<mys.minDistance(str1,str2); }
可以 const size_t lenword1 = word1.size()
const size_t lenword2 = word2.size()
int record[lenword1+1][lenword2+1];
这样定义数组