dp

We are given an array A of N lowercase letter strings, all of the same length.

Now, we may choose any set of deletion indices, and for each string, we delete all the characters in those indices.

For example, if we have an array A = [“babca”,”bbazb”] and deletion indices {0, 1, 4}, then the final array after deletions is [“bc”,”az”].

Suppose we chose a set of deletion indices D such that after deletions, the final array has every element (row) in lexicographic order.

For clarity, A[0] is in lexicographic order (ie. A[0][0] <= A[0][1] <= … <= A[0][A[0].length - 1]), A[1] is in lexicographic order (ie. A[1][0] <= A[1][1] <= … <= A[1][A[1].length - 1]), and so on.

Return the minimum possible value of D.length.

Input: [“babca”,”bbazb”]
Output: 3
Explanation: After deleting columns 0, 1, and 4, the final array is A = [“bc”, “az”].
Both these rows are individually in lexicographic order (ie. A[0][0] <= A[0][1] and A[1][0] <= A[1][1]).
Note that A[0] > A[1] - the array A isn’t necessarily in lexicographic order.

  • The subproblem can be converted to find the length of maximum increasing subsequence.
    • So A[k][i] > A[k][j]
  • The result is that each string should be increasing by deleting some characters.
    • every string must be increasing by deleting the character on i =>
    • we need to delete a character when A[k][i] < A[k][j] (i > j) =>
    • so we need to find whether all strings can satisfy A[x][i] < A[x][j] (x >=0 && x < rows) =>
    • if one string can not satisfy this, then we can’t plus one; otherwise, the length of subsequence should be added one.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
int minDeletionSize(vector<string>& A) {
int row = A.size();
int col = A[0].size();
vector<int> dp(col, 1);
int res = INT_MAX;
for(int i = 0; i < col; i++){
for(int j = 0; j < i; j++){
int k = 0;
for(; k < row; k++){
if(A[k][j] > A[k][i])
break;
}
if(k == row && dp[j] + 1 > dp[i])
dp[i] = dp[j] + 1;
}
res = min(res, col - dp[i]);
}
return res;
}