一、类型描述
Two Sequences 的题目一般会提供两个sequence,一般问最大/最小、true/false、count(*)这几类的问题。
其中,Two Sequences的动态规划题目的四要素:
- state:dp[i][j] 一般表示 第一个sequence的前i个字符 和 第二个sequence的前j个字符 怎么怎么样。
- Initialization: 这类型动态规划一般初始化dp数组的方式是根据题目的含义初始化第一行和第一列。
- function:解决动态规划的function问题,就是找到当前待解决问题dp[i][j] 和 前面解决过的问(例如,dp[i - 1][j]、dp[i][j - 1])的之间的关系。
- answer:dp[s1.length()][s2.length()]
二、Leetcode题目举例
97. Interleaving String hard
Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2.
Example 1:Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true
Example 2:
Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false
题目中,提供了两个source string,一个目标string,问的也是true or false的问题,因此可以考虑two sequences的解法。
- 取状态函数为dp[i][j] 表示 s1的前i个字符 和 s2的前j个字符 能否组成 s3的前 i + j 个字符。
- dp[i][j] 和sub question之间的关系:
需要求的:dp[i][j]
之前求得结果的子问题:dp[i - 1][j]、dp[i][j - 1] .......
优先考虑能否从靠近dp[i][j]的子问题求解:可以发现,可以更具s3的前(i+j)个字符的最后一个字符 来自于 s1 还是 s2 来分类:
因此 dp[i][j] = (dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1)) || (dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1));
Java Solution:
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
if (s3.length() != s1.length() + s2.length()) { return false; }
// state dp[i][j] 表示s1的前i个字符 和 s2的前j个字符 能否组成s3的前(i + j) 个字符
boolean[][] dp = new boolean[s1.length() + 1][s2.length() + 1];
// initialization
// dp[0][j] :s1的前0个字符 和 s2的前j个字符 能否组成 s3的前j个字符?
for (int j = 0; j < dp[0].length; j++) {
// 要判断两个字符串是否相等, 必须用字符串的equals方法来比较
dp[0][j] = s2.substring(0, j).equals(s3.substring(0, j));
//dp[0][j] = s2.substring(0, j) == s3.substring(0, j); // 比较的是两个字符串的reference,并不是实际是否相等,因此这么写是错的
}
// dp[i][0] 同理
for (int i = 0; i < dp.length; i++) {
dp[i][0] = s1.substring(0, i).equals(s3.substring(0, i));
//dp[i][0] = s1.substring(0, i) == s3.substring(0, i); // 错误
}
// function
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
dp[i][j] = (dp[i - 1][j] && (s1.charAt(i - 1) == s3.charAt(i + j - 1))) || (dp[i][j - 1] && (s2.charAt(j - 1) == s3.charAt(i + j - 1)));
}
}
// answer
return dp[s1.length()][s2.length()];
}
}
2. 1143. Longest Common Subsequence Medium
Given two strings text1 and text2, return the length of their longest common subsequence.
A subsequence of a string is a new string generated from the original string with some characters(can be none) deleted without changing the relative order of the remaining characters. (eg, "ace" is a subsequence of "abcde" while "aec" is not). A common subsequence of two strings is a subsequence that is common to both strings.
If there is no common subsequence, return 0.
Example1Input: text1 = "abcde", text2 = "ace"
Output: 3
Explanation: The longest common subsequence is "ace" and its length is 3.
Example2
Input: text1 = "abc", text2 = "abc"
Output: 3
Explanation: The longest common subsequence is "abc" and its length is 3.
原文地址:https://www.cnblogs.com/isguoqiang/p/11529981.html