您的位置:首页 > 其它

72. Edit Distance(动态规划中二维降一维)

2017-08-19 16:42 316 查看

题目:

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[i][j]代表word1[0,i-1] conver to word2[0,j-1]的步骤,有以下几种情况

word1[i]==word2[j],dp[i][j]=dp[i-1][j-1],有人会问为什么不是插入,删除,替换中的最小值,这是一种贪心算法的思想
word1[i]!=word2[j],有三种情况

插入,dp[i][j]=dp[i-1][j]+1
删除,dp[i][j]=dp[i][j-1]+1
替换,dp[i][j]=dp[i-1][j-1]+1

这样可以写出代码

代码:

class Solution {
public:
int minDistance(string word1, string word2) {
int m=word1.size(),n=word2.size();
vector<vector<int>> dp(m+1,vector<int>(n+1,0));
for(int i=0;i<m+1;i++)
dp[i][0]=i;
for(int j=0;j<n+1;j++)
dp[0][j]=j;
for(int i=1;i<m+1;i++){
for(int j=1;j<n+1;j++){
if(word1[i-1]==word2[j-1])
dp[i][j]=dp[i-1][j-1];
else
dp[i][j]=min(dp[i-1][j-1]+1,min(dp[i-1][j]+1,dp[i][j-1]+1));
}
}
return dp[m]
;
}
};


提高:

在阅读网上大佬的代码时发现,由于用到的dp[i-1][j-1],dp[i-1][j],dp[i][j-1],不需要m*n数组,所以可以将dp[i][j]二维数组降维变为一维数组,从而将空间复杂度从O(mn)变为O(m)或者O(n)
具体理解方式:

设置一个两列的数组,第一列名为pre(previous的缩写),第二列名为cur(current的缩写)
第一次循环时,由于pre列处于第一列,故第一列的值等于对应的行的值,此时的dp[i-1][j-1]就是pre列的第一个值,dp[i][j]就是cur列的第二个值
而dp[i-1[j]就可以表示为cur列的前一个值,即cur[i-1],由于cur[i]=cur[i]+1可以理解为现在的值等于过去的值+1,所以dp[i][j-1]可以表示为cur[i]

class Solution {
public:
int minDistance(string word1, string word2) {
int m = word1.length(), n = word2.length();
vector<int> cur(m + 1, 0);
for (int i = 1; i <= m; i++)
cur[i] = i;
for (int j = 1; j <= n; j++) {
int pre = cur[0];
cur[0] = j;       //pre列在向current列转换时,第一个值在第一行,等于列的值
for (int i = 1; i <= m; i++) {
int temp = cur[i];
if (word1[i - 1] == word2[j - 1])
cur[i] = pre;
else cur[i] = min(pre + 1, min(cur[i] + 1, cur[i - 1] + 1));   //右边的cur[i]表示pre列的,即dp[i][j-1]
pre = temp;
}
}
return cur[m];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: