# 955. Delete Columns to Make Sorted II

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 = ["abcdef","uvwxyz"]` and deletion indices `{0, 2, 3}`, then the final array after deletions is `["bef","vyz"]`.

Suppose we chose a set of deletion indices `D` such that after deletions, the final array has its elements in lexicographic order (`A[0] <= A[1] <= A[2] ... <= A[A.length - 1]`).

Return the minimum possible value of `D.length`.

Example 1:

``````Input: ["ca","bb","ac"]
Output: 1
Explanation:
After deleting the first column, A = ["a", "b", "c"].
Now A is in lexicographic order (ie. A[0] <= A[1] <= A[2]).
We require at least 1 deletion since initially A was not in lexicographic order, so the answer is 1.
``````

Example 2:

``````Input: ["xc","yb","za"]
Output: 0
Explanation:
A is already in lexicographic order, so we don't need to delete anything.
Note that the rows of A are not necessarily in lexicographic order:
ie. it is NOT necessarily true that (A[0][0] <= A[0][1] <= ...)
``````

Example 3:

``````Input: ["zyx","wvu","tsr"]
Output: 3
Explanation:
We have to delete every column.
``````

Note:

1. `1 <= A.length <= 100`
2. `1 <= A[i].length <= 100`

``````class Solution {
public:
int minDeletionSize(vector<string>& A) {
int res = 0, m = A.size(), n = A[0].size(), i = 0, j = 0;
vector<int> sorted(m - 1);
for (j = 0; j < n; ++j) {
for (i = 0; i < m - 1; ++i) {
if (!sorted[i] && A[i][j] > A[i + 1][j]) {
++res;
break;
}
}
if (i < m - 1) continue;
for (i = 0; i < m - 1; ++i) {
sorted[i] |= A[i][j] < A[i + 1][j];
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/955

Delete Columns to Make Sorted

https://leetcode.com/problems/delete-columns-to-make-sorted-ii/

https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/203171/C%2B%2B-12-ms-brute-force

https://leetcode.com/problems/delete-columns-to-make-sorted-ii/discuss/203182/JavaC%2B%2BPython-Greedy-Solution-O(MN)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation