dp:编辑距离

Leetcode,EditDistance
分析
设状态为 f[i][j],表示 A[0,i] 和 B[0,j] 之间的最小编辑距离。设 A[0,i] 的形式是 str1c,
B[0,j] 的形式是 str2d,

  1. 如果 c==d,则 f[i][j]=f[i-1][j-1];
  2. 如果 c!=d,
    (a) 如果将 c 替换成 d,则 f[i][j]=f[i-1][j-1]+1;
    (b) 如果在 c 后面添加一个 d,则 f[i][j]=f[i][j-1]+1;
    © 如果将 c 删除,则 f[i][j]=f[i-1][j]+1;

力扣官方题解
ikaruga【编辑距离】入门动态规划,你定义的 dp 里到底存了啥

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// 二维动规,时间复杂度 O(n*m),空间复杂度 O(n*m)
int solution(const string &word1, const string &word2)
{
	const int n = word1.size();
	const int m = word2.size();

	vector<vector<int>> vec(n + 1, vector<int>(m + 1, 0));
	for (int i = 0; i <= n; ++i)
		vec[i][0] = i;
	for (int j = 0; j <= m; ++j)
		vec[0][j] = j;
			
	for ( int i = 1; i <= n; ++i )
	{
		for ( int j = 1; j <= m; ++j)
		{
			if (word1[i - 1] == word2[j - 1])
				vec[i][j] = vec[i - 1][j - 1];
			else
			{
				int mn = std::min( vec[i - 1][j], vec[i][j - 1]);
				vec[i][j] = 1 + std::min( vec[i - 1][j - 1], mn );
			}
		}
	}

	return vec[n][m];
}

//二维动规 + 滚动数组 时间复杂度 O(n*m),空间复杂度 O(n)
int solution1(const string &word1, const string &word2)
{
	if (word1.length() > word2.length())
		return solution1(word2, word1);

	vector<int> vec(word2.length() + 1);
	int  upper_left = 0;	//额外用一个变量记录 f[i-1][j-1]

	for (int i = 0; i <= word2.size(); ++i)
		vec[i] = i;

	for ( int i = 1; i <= word1.size(); ++i )
	{
		upper_left = vec[0];
		vec[0] = i;

		for (int j = 1; j <= word2.size(); ++j)
		{
			int upper = vec[j];
			if (word1[i - 1] == word2[j - 1])
				vec[j] = upper_left;
			else
				vec[j] = 1 + std::min( upper_left, std::min(vec[j], vec[j - 1]));

			upper_left = upper;
		}
	}
	
	return vec[word2.length()];
}


int main()
{
	{
		string word1 = "horse", word2 = "ros";
		cout << solution1(word1, word2) << endl;	//3
	}
	{
		string word1 = "intention", word2 = "execution";
		cout << solution1(word1, word2) << endl;	//5
	}

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值