Leetcode 72.Edit Distance
编辑距离问题是一个经典问题。具体的解决方法如下:
题目代码如下:
class Solution {
public:
int minDistance(string word1, string word2) {
const int m = word2.size();
const int n = word1.size();
if (m == 0) return n;
if (n == 0) return m;
//Next we will use a matrix by m*n to store information,C(i,j) = 1 if word1(j) == word2(i), else value is zero.
int **c = new int*[m];
for (int i = 0; i < m; i++) {
c[i] = new int[n];
for (int j = 0; j < n; j++) {
if (word1[j] == word2[i]) {
c[i][j] = 1;
} else c[i][j] = 0;
}
}
//Let f(i,j) be that minimum numbers of steps required to convert word1(0,j-1) to word2(0,i-1)
//then f(i,j) = min{f(i-1,j)+1,f(i,j-1)+1,f(i-1,j-1)+abs(1-c(i,j))};
int flag1 = 0, flag2 = 0;//represent whether there has been a character equals the first of word1 or word2
int **f = new int*[m];
f[0] = new int[n];
f[0][0] = 1 - c[0][0];
flag1 = flag2 = c[0][0];
int tmp;
for (int i = 1; i < n; i++) {
tmp = (!flag2 && c[0][i])?0:1;
f[0][i] = f[0][i-1] + tmp;
flag2 = flag2 || c[0][i];
}
for (int i = 1; i < m; i++) {
f[i] = new int[n];
tmp = (!flag1 && c[i][0])?0:1;
f[i][0] = f[i-1][0] + tmp;
flag1 = flag1 || c[i][0];
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
f[i][j] = min(f[i-1][j]+1,f[i][j-1]+1);
f[i][j] = min(f[i][j],f[i-1][j-1]+1-c[i][j]);
}
}
return f[m-1][n-1];
}
};
Leetcode 85.Maximum Rectangle
算法代码如下:
class Solution {
public:
int maximalRectangle(vector<vector<char> > &matrix) {
if(matrix.empty()) return 0;
const int m = matrix.size();
const int n = matrix[0].size();
int left[n], right[n], height[n];
fill_n(left,n,0); fill_n(right,n,n); fill_n(height,n,0);
int maxA = 0;
for(int i=0; i<m; i++) {
int cur_left=0, cur_right=n;
for(int j=0; j<n; j++) { // compute height (can do this from either side)
if(matrix[i][j]=='1') height[j]++;
else height[j]=0;
}
for(int j=0; j<n; j++) { // compute left (from left to right)
if(matrix[i][j]=='1') left[j]=max(left[j],cur_left);
else {left[j]=0; cur_left=j+1;}
}
// compute right (from right to left)
for(int j=n-1; j>=0; j--) {
if(matrix[i][j]=='1') right[j]=min(right[j],cur_right);
else {right[j]=n; cur_right=j;}
}
// compute the area of rectangle (can do this from either side)
for(int j=0; j<n; j++)
maxA = max(maxA,(right[j]-left[j])*height[j]);
}
return maxA;
}
};