Algorithm-week8

来源:互联网 发布:石油进出口数据 编辑:程序博客网 时间:2024/06/07 00:19

Week8

Program--Medium--712.Minimum ASCII Delete Sum for Two Strings

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

Example 1:

Input: s1 = "sea", s2 = "eat"Output: 231Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.Deleting "t" from "eat" adds 116 to the sum.At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.

Example 2:

Input: s1 = "delete", s2 = "leet"Output: 403Explanation: Deleting "dee" from "delete" to turn the string into "let",adds 100[d]+101[e]+101[e] to the sum.  Deleting "e" from "leet" adds 101[e] to the sum.At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.

Note:

  • 0 < s1.length, s2.length <= 1000.
  • All elements of each string will have an ASCII value in [97, 122].

    题目解析:

    这是一道标准的动态规划的题目,动态规划的题目的重点是状态的确定以及状态之间的转移关系。对于最少多少枚不同面值硬币能组成一定金额的钱的问题,它的状态就是组成金额n前的n-1个状态,即组成金额为1,2,3....等。通过求解前几个状态的最小值,从中选择最小的加1,我们就能够求解状态n的最小值。所以动态规划似乎也有分治的思想在里面,但是这里的子问题间是相互影响的,不能单纯由子问题拼接而成,只能一步一步由简单状态向复杂状态转化。

    这个问题也是类似的,整个问题可划分为不同状态子问题求解的最优转化,求两段长的字符串求最小删除字符和以致两段字符串相同,可以分解为两段更小的字符串求相同问题,不过比原问题少一两个字符。对于长度分别为(m, n)的字符串,只要我们求得(m-1, n)或者(m, n-1)长字符串的问题求解,在从中选择最小值作为原问题的上一个状态值即可。下面是算法的基本流程:

    1.初始化起始基本状态,即长度为0与第二个字符串不同长度间最小删除得出相同字符串就是将所有字符都删除。

    2.进行状态转移,对于字符串1中不同长度的子串,与字符传2的不同长度的子串找最小删除字符和。

    3.在一个字符串增长时,假设增加的字符与另一个字符串尾字符相同,则找到相同字符串中的一个字符,这时候不用删除,代价等于上一个状态。

    4.在一个字符串增长时,假设增加的字符与另一个字符串尾不同,则需要删除一个字符。假设当前状态为长度[m, n],则前一个状态可能为[m-1, n]和[m, n-1],那么,我们就从中选取最小的,保持前面字符串求解中找到的最多相同的状态,因为两个字符串中相同的越多,那么删除的就越小。

    代码:

    class Solution {public:    int minimumDeleteSum(string s1, string s2) {        int m = s1.length();        int n = s2.length();        vector<vector<int>> cost(m + 1, vector<int>(n + 1, 0));        cost[0][0] = 0;        for (int j = 1; j < n + 1; j++) {            cost[0][j] = cost[0][j - 1] + s2[j - 1];        }                for (int i = 1; i < m + 1; i++) {            cost[i][0] = cost[i - 1][0] + s1[i - 1];            for (int j = 1; j < n + 1; j++) {                if (s1[i - 1] == s2[j - 1]) {                    cost[i][j] = cost[i - 1][j - 1];                } else {                    cost[i][j] = min(cost[i - 1][j] + s1[i - 1], cost[i][j - 1] + s2[j - 1]);                }            }        }        return cost[m][n];    }};



  • 原创粉丝点击