题解 | #最小编辑代价#

最小编辑代价

http://www.nowcoder.com/practice/05fed41805ae4394ab6607d0d745c8e4

编辑距离变型题
表示将的前个元素转换成的前个元素的最小代价,状态转移方程:
(1);//啥都不操作;
(2),

时间复杂度:
空间复杂度:

class Solution {
public:
    /**
     * min edit cost
     * @param str1 string字符串 the string
     * @param str2 string字符串 the string
     * @param ic int整型 insert cost
     * @param dc int整型 delete cost
     * @param rc int整型 replace cost
     * @return int整型
     */
    int minEditCost(string str1, string str2, int ic, int dc, int rc) {
        // write code here
        int m = str1.length(), n = str2.length();
        int dp[m + 1][n + 1];
        memset(dp, 0, sizeof(dp));
        //边界
        for(int i = 1; i <= m; i ++) dp[i][0] = dp[i - 1][0] + dc;
        for(int j = 1; j <= n; j ++) dp[0][j] = dp[0][j - 1] + ic;
        //dp
        for(int i = 1; i <= m; i ++){
            for(int j = 1; j <= n; j ++){
                if(str1[i - 1] == str2[j - 1]) dp[i][j] = dp[i - 1][j - 1];
                else dp[i][j] = min({dp[i - 1][j - 1] + rc,
                                     dp[i][j - 1] + ic,
                                     dp[i - 1][j] + dc});
            }
        }
        return dp[m][n];
    }
};
全部评论

相关推荐

ResourceUt...:楼主有自己的垃圾箱,公司也有自己的人才库
点赞 评论 收藏
分享
notbeentak...:孩子,说实话,选择很重要,可能你换一个方向会好很多,但是现在时间不太够了,除非准备春招
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务