题目来源
https://leetcode-cn.com/problemset/all/
他山之石:
https://www.zhihu.com/question/23995189/answer/1094101149
例题1: 最长回文子串
分析
class Solution:
def longestPalindrome(self, s: str) -> str:
if s == s[::-1]:
return s
n = len(s)
max_len = 1
begin = 0
dp = [[False] * n for _ in range(n)]
for i in range(n):
dp[i][i] = True
# 枚举子串长度:
for L in range(2, n + 1):
for i in range(n):
j = L + i - 1
if j >= n:
break
if s[i] != s[j]:
dp[i][j] = False
else:
if j - i < 3:
dp[i][j] = True
else:
dp[i][j] = dp[i + 1][j - 1]
if dp[i][j] and L > max_len:
max_len = L
begin = i
return s[begin:begin + max_len]
例题2: 最大正方形
分析
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
"""
状态转移方程:dp(i,j)=min(dp(i?1,j),dp(i?1,j?1),dp(i,j?1))+1
"""
row_num = len(matrix)
col_num = len(matrix[0])
dp = [[0] * col_num for _ in range(row_num)]
max_rec_length = 0
for i in range(row_num):
for j in range(col_num):
if matrix[i][j] == ‘0‘:
continue
dp[i][j] = min(dp[i-1][j], dp[i][j-1], dp[i-1][j-1]) + 1
max_row = max(dp[i])
max_rec_length = max_row if max_row > max_rec_length else max_rec_length
return max_rec_length ** 2
例题3 最大矩形
分析
class Solution(object):
def maximalRectangle(self, matrix):
row_len = len(matrix)
if row_len == 0:
return 0
col_len = len(matrix[0])
dp = [[0] * col_len for _ in range(row_len)]
dp[0][0] = int(matrix[0][0])
max_squre = dp[0][0]
for i in range(row_len):
for j in range(col_len):
if i == 0 and j == 0:
continue
if matrix[i][j] == ‘1‘:
if j == 0:
dp[i][j] = 1
else:
dp[i][j] = dp[i][j-1] + 1
for i in range(row_len):
for j in range(col_len):
if matrix[i][j] == ‘0‘:
continue
width = dp[i][j]
area = width
for k in range(i - 1, -1, -1):
width = min(width, dp[k][j])
area = max(area, (i-k+1) * width)
max_squre = max(max_squre, area)
return max_squre
例题4 编辑距离
分析
知乎@帅地
dp含义:当字符串 word1 的长度为 i,字符串 word2 的长度为 j 时,将 word1 转化为 word2 所使用的最少操作次数为 dp[i] [j]
dp关系:dp[i] [j] = min(dp[i-1] [j-1],dp[i] [j-1],dp[[i-1] [j]]) + 1;
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n1 = len(word1)
n2 = len(word2)
dp = [[0] * (n2+1) for _ in range(n1+1)]
for j in range(1, n2+1):
dp[0][j] = dp[0][j-1] + 1
for i in range(1, n1 + 1):
dp[i][0] = dp[i-1][0] + 1
for i in range(1, n1+1):
for j in range(1, n2+1):
if word1[i-1] == word2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min(dp[i-1][j-1], dp[i-1][j], dp[i][j-1]) + 1
return dp[n1][n2]
原文:https://www.cnblogs.com/tenslib/p/14839202.html