最小编辑代价
来源:互联网 发布:软件开发 私活 价格 编辑:程序博客网 时间:2024/06/08 03:59
/*********************************************************************************
*description:最小编辑代价
* 给定两个字符串str1和str2,再给定三个整数ic、dc、rc,
* 代表插入、删除和替换一个字符的代价,求str1编辑为str2的最小代价
* 如:str1=“abc” str2=“adc”,ic=5,dc=3,rc=2
* 返回2
*description:最小编辑代价
* 给定两个字符串str1和str2,再给定三个整数ic、dc、rc,
* 代表插入、删除和替换一个字符的代价,求str1编辑为str2的最小代价
* 如:str1=“abc” str2=“adc”,ic=5,dc=3,rc=2
* 返回2
*********************************************************************************/
#include<iostream>#include<vector>#include<string>using namespace std;//方法:时间复杂度O(M*N),空间复杂度O(M*N)//经典动态规划问题,创建数组dp[M+1][N+1]//dp[i][j]代表str1[0...i-1]编辑为str2[0...j-1]的最小代价//dp[0][0]=0,空串编辑为空串的代价//dp[i][0]:str1[0...i-1]编辑为空串的代价:i*dc//dp[0][j]:空串编辑为str2[0...j-1]的代价:j*ic//dp[i][j]:下面4种情况的最小// 1.dp[i-1][j]+dc// 2.dp[i][j-1]+ic// 3.dp[i-1][j-1]+rc 当str1[i-1]!=str2[j-1]// 4.dp[i-1][j-1] 当str1[i-1]==str2[j-1]//得到dp之后,右下角元素即为结果。int minCost(string str1, string str2, int ic, int dc, int rc){ int M = str1.size(); int N = str2.size(); vector<vector<int>> dp(M+1, N+1); for (int i = 0; i <= M; i++) dp[i][0] = i * dc; for (int j = 0; j <= N; j++) dp[0][j] = j * ic; for (int i = 1; i < M+1; i++) { for (int j = 1; j < N+1; j++) { dp[i][j] = dp[i-1][j]+dc < dp[i][j-1]+ic ? dp[i-1][j]+dc : dp[i][j-1]+ic; if (str1[i-1] == str2[j-1]) dp[i][j] = dp[i][j] < dp[i-1][j-1] ? dp[i][j] : dp[i-1][j-1]; else dp[i][j] = dp[i][j] < dp[i-1][j-1]+rc ? dp[i][j] : dp[i-1][j-1]+rc; } } return dp[M][N];}int main_09(){ string str1 = "abc"; string str2 = "adc"; cout << minCost(str1, str2, 5, 3, 29 ); return 0;}
阅读全文
0 0
- 最小编辑代价
- 最小编辑代价
- 最小编辑代价
- 最小编辑代价
- godfrey_88 最小编辑代价
- 最小编辑代价
- 最小编辑代价
- 最小编辑代价
- 【动态规划】最小编辑代价
- 最小编辑代价---动态规划
- 最小编辑代价 动态规划
- 最小编辑代价(动态规划)
- 最小编辑代价(动态规划)
- 最小编辑代价(动态规划)
- 递归与动态规划---最小编辑代价
- 动态规划系列问题-最小编辑代价
- 最小代价
- 最小代价;;;;
- CgLib动态代理初步实践
- MYSQL必知必会 学习笔记一
- Android Studio 出现 Gradle's dependency cache may be corrupt 解决办法
- 1.数据结构绪论
- 2017多校6 1002 hdu 6097
- 最小编辑代价
- 星球闪烁高亮
- 沉浸式状态栏的实现
- 串的匹配算法
- 二叉排序
- 题目264-国王的魔镜
- 字符串的交错组成
- 第七天
- leetcode(169). Majority Element