# 960. Delete Columns to Make Sorted III

**<font color=red>难度: Hard</font>**

## 刷题内容

> 原题连接

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

> 内容描述

```
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.

 

Example 1:

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.
Example 2:

Input: ["edcba"]
Output: 4
Explanation: If we delete less than 4 columns, the only row won't be lexicographically sorted.
Example 3:

Input: ["ghi","def","abc"]
Output: 0
Explanation: All rows are already lexicographically sorted.
 

Note:

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

## 解题方案

> 思路 1
******- 时间复杂度: O(m * n^2)******- 空间复杂度: O(n)******


dp[i]代表每个A中的字符串从第i个字符开始取的话，可以取得的最长子序列长度

例如["babca","bbazb"]

- dp[4]代表输入为["a","b"]时，删除最少列使得题目条件满足后的字符串的长度，这里知道dp[4] = 1，因为最长满足条件的字符串为["a","b"]
- dp[3]代表输入为["ca","zb"]时，删除最少列使得题目条件满足后的字符串的长度，这里知道dp[3] = 1，因为最长满足条件的字符串为["c","z"]或者["a","b"]
- dp[2]代表输入为["bca","azb"]时，删除最少列使得题目条件满足后的字符串的长度，这里知道dp[2] = 2，因为最长满足条件的字符串为["bc","az"]
- dp[1]代表输入为["abca","bazb"]时，删除最少列使得题目条件满足后的字符串的长度，这里知道dp[1] = 2，因为最长满足条件的字符串为["aa","bb"]
- dp[0]代表输入为["babca","bbazb"]时，删除最少列使得题目条件满足后的字符串的长度，这里知道dp[0] = 2，因为最长满足条件的字符串为["aa","bb"]

因为dp[0] = 2，所以满足条件的最长的字符串长度为2，因此我们至少要删除掉3列才行，return 3

时间复杂度中的m为input中字符串的个数，n为input中每个字符串的长度



```python
class Solution:
    def minDeletionSize(self, A):
        """
        :type A: List[str]
        :rtype: int
        """
        dp = [1] * len(A[0])
        
        for i in range(len(A[0])-2, -1, -1):
            for j in range(i+1, len(A[0])):
                if all(row[i] <= row[j] for row in A):
                    dp[i] = max(dp[i], dp[j]+1)
        return len(A[0]) - max(dp)
```





























