Catalogue
- Input Parameters have two Sequences or Strings
- Two Sequences Matching?
1 Longest
LintCode 79. Longest Common Substring
1 | class Solution: |
LintCode 77. Longest Common Subsequence
- State : dp[i][j] means Longest Common Subsequence for A[0…i-1] and B[0…j-1]
- Init : dp[i][0] = dp[0][j] = 0
- Deduction Formula :
1 | # Time : O(mn), Space : O(mn) |
- Space Improvement
dp[i][j] -> dp[i % 2][j]
1 | # Space : O(n) |
2 Exist
10. Regular Expression Matching
- Case Analysis!!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class Solution(object):
def isMatch(self, s, p):
m, n = len(s), len(p)
dp = [[False] * (n+1) for _ in range(m+1)]
dp[0][0] = True
for i in range(n):
if p[i] == "*":
dp[0][i+1] = dp[0][i-1]
for i in range(m):
for j in range(n):
if s[i] == p[j] or p[j] == '.':
dp[i+1][j+1] = dp[i][j]
elif p[j] == '*':
dp[i+1][j+1] = dp[i+1][j-1]
if p[j-1] == '.' or p[j-1] == s[i]:
dp[i+1][j+1] = dp[i+1][j+1] or dp[i][j+1]
return dp[-1][-1]
97. Interleaving String
- Three String!!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23class Solution(object):
def isInterleave(self, s1, s2, s3):
m, n, l = len(s1), len(s2), len(s3)
if m + n != l:
return False
dp = [[False] * (n+1) for _ in range(m+1)]
dp[0][0] = True
for i in range(m):
if s1[i] == s3[i]:
dp[i+1][0] = dp[i][0]
for j in range(n):
if s2[j] == s3[j]:
dp[0][j+1] = dp[0][j]
for i in range(m):
for j in range(n):
if s3[i+j+1] == s1[i]:
dp[i+1][j+1] = dp[i+1][j+1] or dp[i][j+1]
if s3[i+j+1] == s2[j]:
dp[i+1][j+1] = dp[i+1][j+1] or dp[i+1][j]
return dp[-1][-1]
3 Count
72. Edit Distance
1 | class Solution(object): |
161. One Edit Distance
- a littel like “Edit Distance”, but totally different solution!!! no dp here!
1 | class Solution(object): |
801. Minimum Swaps To Make Sequences Increasing
- State
swap[i]: The cost of making both sequences increasing up to the first i columns in condition that we swap A[i] and B[i]
notswap: The cost of making both sequences increasing up to the first i columns in condition that we do not swap A[i] and B[i] - Init : swap[0] = 1; notswap[0] = 0
1 | class Solution(object): |
- 我总是想记录上一个有没有swap,来record最优解,困于DFS的写法了!
- 跳开DFS的方式还是定义对DP的State,如果能想到定义两个State一个表示Swap一个表示不Swap,后面思路就很顺了!