960. Delete Columns to Make Sorted III
阿新 • • 發佈:2018-12-16
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}
["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
思路:DP,dp[i]表示以第i列結尾的情況下,前面那些字元需要刪除的最小列數(後面的一定會刪掉,因為要以當前列結尾)
class Solution(object):
def minDeletionSize(self, A):
"""
:type A: List[str]
:rtype: int
"""
dp=[len(A)-1]*len(A[0])
dp[0]=0
for i in range(1,len(dp)):
dp[i]=i
for j in range(i):
if all(A[k][i]>=A[k][j] for k in range(len(A))):
dp[i]=min(dp[i],dp[j]+i-j-1)
dp2 = [dp[i]+len(dp)-i-1 for i in range(len(dp))]
return min(dp2)
s=Solution()
print(s.minDeletionSize(["babca","bbazb"]))
print(s.minDeletionSize(["edcba"]))
print(s.minDeletionSize(["ghi","def","abc"]))