# LeetCode中的动态规划题目解答（3）

class Solution {
public:
int findLength(vector<int>& A, vector<int>& B) {

int m = A.size();
int n = B.size();

int ** matrix = new int*[m+1];

for(int i = 0; i < m+1; i++)
{
matrix[i] = new int[n+1];
for(int j = 0; j < n+1; j++)
{
matrix[i][j] = 0;
}
}

int max = 0;

for(int i = 1; i < m+1; i++)
{
for(int j = 1; j < n+1; j++)
{
if(A[i-1]==B[j-1])
{
matrix[i][j] = 1 + matrix[i-1][j-1];
max = max > matrix[i][j] ? max : matrix[i][j];
}
else
matrix[i][j] = 0;
}
}

return max;
}
};

class Solution {
public:
int minDistance(string word1, string word2) {

int m = word1.size();
int n = word2.size();

if(m==0)  return n;
if(n==0)  return m;

int ** matrix = new int*[m+1];

int i = 0;
int j = 0;
int p = 0;
int q = 0;

for(i = 0; i < m+1; i++)
{
matrix[i] = new int[n+1];
matrix[i][0] = 0+i;
}

for(j = 0; j < n+1; j++)
{
matrix[0][j] = 0+j;
}

for(i = 1; i < m+1; i++)
{
for(j = 1; j < n+1; j++)
{

p = matrix[i][j-1] + 1 < matrix[i-1][j] + 1 ? matrix[i][j-1] + 1 : matrix[i-1][j] + 1;

if(word1[i-1]==word2[j-1])
{
q = matrix[i-1][j-1];
}
else
{
q = matrix[i-1][j-1] + 1;
}

matrix[i][j] = p < q ? p : q;
}
}

return matrix[m][n];

}
};

（本文完）

• # 波兰表达式（Reverse Polish Notation）（#150）

©️2019 CSDN 皮肤主题: 精致技术 设计师: CSDN官方博客