动态规划(字符串各种最长序列,子串等问题)
文章目录
- 动态规划(字符串各种最长序列,子串等问题)
- 1.[判断子序列](https://leetcode-cn.com/problems/is-subsequence/)
- 2.[最大子序和](https://leetcode-cn.com/problems/maximum-subarray/)
- 3.[乘积最大子序列](https://leetcode-cn.com/problems/maximum-product-subarray/)
- 4.[最长重复子数组](https://leetcode-cn.com/problems/maximum-length-of-repeated-subarray)
- 5.[最长公共子序列](https://leetcode-cn.com/problems/longest-common-subsequence/)
- 6.[最长定差子序列](https://leetcode-cn.com/problems/longest-arithmetic-subsequence-of-given-difference/)
- 7.[最长回文子序列](https://leetcode-cn.com/problems/longest-palindromic-subsequence/)
- 8.[最长回文子串](https://leetcode-cn.com/problems/longest-palindromic-substring)
- 9.[最长上升子序列](https://leetcode-cn.com/problems/longest-increasing-subsequence)
- 10.[最长连续递增序列](https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence)
- 11.[最长递增子序列的个数](https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence)
- 12.[最长连续序列](https://leetcode-cn.com/problems/longest-consecutive-sequence)
- 13.[最长和谐子序列](https://leetcode-cn.com/problems/longest-harmonious-subsequence)
- 14.[编辑距离](https://leetcode-cn.com/problems/edit-distance)
1.判断子序列
我们要知道子序列跟子串是有区别的,子序列并不一定要求连续,子串则是要求连续的,对于这道题,遍历字符串s,判断t中是否包含每个s的每个字符是否在t中出现,不单单这样,还需要用index保存每次找到的出现在t中符合要求的字符的位置,保证下次检索是从上次的索引往后检索,保证s的字符顺序
/**
* 判断子序列
* @param s
* @param t
* @return
*/
public boolean isSubsequence(String s, String t) {
if(s.length() == 0){
return true;
}
int index = -1;
for(char c : s.toCharArray()){
//判断完一个字符是否在t中后,应从后序index再开始判断
index = t.indexOf(c,index + 1);
if(index == -1){
return false;
}
}
return true;
}
2.最大子序和
-
如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字
-
如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字
-
每次比较 sum 和 ans的大小,将最大值置为ans,遍历结束返回结果
-
所以动态方程:
dp[i] = max{dp[i - 1] + nums[i],nums[i]}
go实现:
func maxSubArray(nums []int)int{
if len(nums) == 0{
return 0
}
dp := make([]int, len(nums))
dp[0] = nums[0]
res := nums[0]
for i := 1;i < len(nums);i++{
dp[i] = int(math.Max(float64(dp[i - 1] + nums[i]),float64(nums[i])))
res = int(math.Max(float64(res),float64(dp[i])))
}
return res
}
java实现:
/**
* 最大子序和
* @param nums
* @return
*/
public int maxSubArray(int[] nums) {
if(nums.length == 0){
return 0;
}
int[] dp = new int[nums.length + 1];
dp[0] = nums[0];
int res = nums[0];
for(int i = 1;i < nums.length;i++){
dp[i] = Math.max(dp[i - 1] + nums[i],nums[i]);
res = Math.max(res,dp[i]);
}
return res;
}
3.乘积最大子序列
乘法的话我们需要注意负负得正的情况:
- 原来的最小的乘积是负数的话,乘上下一个负数就会变成一个正数,该正数可能是最大值
- 原来的最大的乘积是正数的话,乘上下一个负数就会变成一个负数,此时该结果可能变成最小值
所以我们需要维护一个最大值和一个最小值,当遇到负数时,最大和最小交换
所以,动态方程:
dp[i] = max{dp[i - 1] * nums[i],nums[i]}
维护最大值最小值:
tempMax = max{tempMax * nums[i],nums[i]}
tempMin = min{tempMin * nums[i],nums[i]}
go实现:
/**
乘积最大子序列
*/
func maxProduct(nums []int)int{
if len(nums) == 0{
return 0
}
res := nums[0]
max := 1
min := 1
for i := 0;i < len(nums);i++{
if nums[i] < 0{
max,min = min,max
}
max = int(math.Max(float64(max * nums[i]),float64(nums[i])))
min = int(math.Min(float64(min * nums[i]),float64(nums[i])))
res = int(math.Max(float64(max),float64(res)))
}
return res
}
java实现:
/**
* 乘积最大子序列
* @param nums
* @return
*/
public int maxProduct(int[] nums) {
if(nums.length == 0){
return 0;
}
int res = nums[0];
int min = 1;
int max = 1;
for(int i = 0;i < nums.length;i++){
//如果下一个要相乘的数是负数,则正负得负,负负得正
//最大的会变成最小的,最小的会变成最大的
if(nums[i] < 0){
int temp = min;
min = max;
max = temp;
}
max = Math.max(nums[i] * max,nums[i]);
min = Math.min(nums[i] * min,nums[i]);
res = Math.max(res,max);
}
return res;
}
4.最长重复子数组
使用动态规划从前往后遍历
dp[i][j]:数组长度为i和j的重复子数组的长度
分析状态转移:
if A[i - 1] == B[j - 1]
dp[i][j] = dp[i - 1][j - 1] + 1
func findLength(A []int, B []int) int {
aLen := len(A)
bLen := len(B)
res := 0
dp := [1001][1001]int{}
for i := 1;i <= aLen;i++{
for j := 1;j <= bLen;j++{
if A[i - 1] == B[j - 1]{
dp[i][j] = dp[i - 1][j - 1] + 1
if dp[i][j] > res {
res = dp[i][j]
}
}
}
}
return res
}
java实现:
/**
* 最长重复子数组
* @param A
* @param B
* @return
*/
public int findLength(int[] A, int[] B) {
int res = 0;
int[][] dp = new int[A.length + 1][B.length + 1];
for (int i = 1; i <= A.length; i++) {
for (int j = 1; j <= B.length; j++) {
if (A[i - 1] == B[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
res = Math.max(dp[i][j], res);
}
}
}
return res;
}
5.最长公共子序列
假设:
i = len(text1)
j = len(text2)
那么原问题就是求解:
text[ 0 … i ] 和 text2[ 0 … j ]的最长公共子序列
那么原问题的子问题就是:
text[ 0 … i - 1 ] 和 text [0 … j - 1]
怎么将原问题和子问题联系起来?
如果 text1(m)==text2(n),那么我们就可以将子问题中的 text1(0,…m-1) 和 text2(0,…n-1) 后面添加两个相同字符递进成当前问题;如果不相等,我们就需要考虑在三个子问题中选择一个较大值了。
所以:
if text1(i) == text2(j)
dp[i][j] = dp[i - 1][j - 1] + 1
else
dp[i][j] = max{dp[i - 1][j],dp[i][j - 1]}
所以:
go实现:
func longestCommonSubsequence(text1 string, text2 string) int {
if len(text1) == 0 || len(text2) == 0{
return 0
}
dp := [1001][1001]int{};
for i := 1;i <= len(text1);i++{
for j := 1;j <= len(text2);j++{
if text1[i - 1] == text2[j - 1]{
dp[i][j] = dp[i - 1][j - 1] + 1
}else{
dp[i][j] = int(math.Max(float64(dp[i - 1][j]),float64(dp[i][j - 1])))
}
}
}
return dp[len(text1)][len(text2)]
}
java实现
public int longestCommonSubsequence(String text1, String text2) {
int len1 = text1.length();
int len2 = text2.length();
int[][] dp = new int[len1+1][len2+1];
for(int i = 1;i < len1;i++){
for(int j = 1;j < len2;j++){
if(text1.charAt(i - 1) == text2.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1] + 1;
}else{
dp[i][j] = Math.max(dp[i - 1][j],dp[i][j - 1]);
}
}
}
return dp[len1][len2];
}
6.最长定差子序列
这道题其实思路比较简单,
dp[i]来记录以数字`i`为结尾的`最长等差子序列`的长度:
- dp[i] = 1 // 表示在 i 之前没有出现等差子序列
- dp[i] = dp[i - difference] + 1 // 表示在 i 之前出现了等差子序列,长度为 dp[i - difference], 而 i 也是满足这个等差序列的,所以等差序列的长度在此基础上加 1 就可以了
因为数组下标不能是负数,所以使用map维护
go实现:
func longestSubsequence(arr []int, difference int) int {
m := make(map[int]int)
max := 0
for _, a := range arr {
if m[a] == 0 {
m[a] = 1
}
max = Max(max, m[a])
m[a + difference] = m[a] + 1
}
return max
}
func Max(x, y int) int {
if x > y {
return x
}
return y
}
java实现:
public int longestSubsequence(int[] arr, int difference) {
// 下标不能存在负数
// int[] dp = new int[arr.length + 1];
// for(int i : arr){
// dp[i] = Math.max(dp[i],dp[i - difference] + 1);
// }
int res = 0;
Map<Integer,Integer> map = new HashMap<>();
for(int i : arr){
int tmp = map.getOrDefault(i - difference,0) + 1;
map.put(i,tmp);
res = Math.max(res,tmp);
}
return res;
}
7.最长回文子序列
双指针,一个从前往后,一个从后往前遍历
状态定义:
dp[i][j] : 从i到j长度区间的最长回文子序列
动态方程:
if s(i) == s(j)
dp[i][j] = dp[i + 1][j - 1] + 2
else
dp[i][j] = max{dp[i + 1][j],dp[i][j - 1]}
java实现:
public int longestPalindromeSubseq(String s) {
if (s == null || s.length() == 0) {
return 0;
}
int n = s.length();
int[][] dp = new int[n][n];
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) {
dp[i][j] = dp[i + 1][j - 1] + 2;
} else {
dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}
8.最长回文子串
定义状态:
dp[l][r]:区间[l,r]的子串时回文子串
状态分析:
dp[l + 1][r - 1]如何推出dp[l][r]是回文子串?
状态转移推导:
dp[l + 1][r - 1]是区间[l + 1,r - 1]的子串
----------------------------------------
想要推出dp[l][r]这个更长区间的子串是回文串需满足:
1. dp[l + 1][r - 1]小区间子串是回文串
2. s[l] == s[r]区间两端字符需相同
3. r - l + 1 == 0 || r - l + 1 == 1意思是当l和r中只有1个字符或者没有字符时
根据以上情况状态转移为:
if s[l] == s[r] && (dp[l + 1][r - 1] || r - l <= 2)
dp[l][r] = dp[l + 1][r - 1] + 2
else
dp[l][r] = max{dp[l + 1][r] , dp[l][r - 1]}
java实现:
public String longestPalindrome(String s) {
int len = s.length();
if(len <= 1){
return s;
}
//记录最长回文串长度
int longestPalindromeLen = 1;
//记录最长的回文串
String longestPalindrome = s.substring(0,1);
boolean[][] dp = new boolean[len][len];
for(int r = 1;r < len;r++){
for(int l = 0;l < r;l++){
if(s.charAt(l) == s.charAt(r) && (r - l <= 2 || dp[l + 1][r - 1])){
dp[l][r] = true;
if(r - l + 1 > longestPalindromeLen){
longestPalindrome = s.substring(l,r + 1);;
longestPalindromeLen = r - l + 1;
}
}
}
}
return longestPalindrome;
}
9.最长上升子序列
我们用
dp[i] 表示数组中索引为 i 结尾的子数组的最长上升子序列的长度
那么我们要求整体最长子序列就是
dp[nums.length - 1]
分析子问题
dp[nums.length - 1]的子问题就是dp[nums.length - 2],以此类推
分析状态转移,怎么由子问题推导得到原问题的最优解
题目意思就是要我们求得最长上升子序列的长度,对于子序列跟子数组的不同之处就在于,子序列可以跳过,元素和元素在数组中不一定是连续排列的,比如
[2,5,3,7,101]是子序列
[10,101]也是子序列
题目让我们求最长的一个上升子序列的长度
我们先遍历所有子数组
for(int i = 0;i < nums.length;i++){
for(int j = 0;j < i;j++){
//以上表达的是区间[j,i]的子数组
}
}
条件,上升
对于子问题如何能得到原问题
这就涉及到如何判断上升这个条件了,显然,这个很简单
nums[i] > nums[j]
nums[i] 可以接在 nums[j]之后(此题要求严格递增),此情况下最长上升子序列长度为 dp[j]+1
nums[i] <= nums[j]
nums[i] 无法接在 nums[j] 之后,此情况上升子序列不成立,跳过。
所以:
public int lengthOfLIS(int[] nums) {
int len = nums.length;
if(len == 0){
return 0;
}
int[] dp = new int[len];
int maxLen = 1;
for(int i = 0;i < len;i++){
int tempLen = 1;
for(int j = 0;j < i;j++){
if(nums[i] > nums[j]){
tempLen = Math.max(dp[j] + 1,tempLen);
}
}
//记录以索引i结尾的子数组的最长上升子序列长度
dp[i] = tempLen;
//记录此时的全局最优解
if(tempLen > maxLen){
maxLen = tempLen;
}
}
return maxLen;
}
10.最长连续递增序列
这道题和上面的最长上升子序列的区别在于,这道题要求的连续上升,即
temp = 1;//记录长度
if nums[i] > nums[i - 1]
temp++ //只有连续递增长度才会增加
else
temp = 1; //否则只能回到初始值,下一次循环
解答:
/**
* 最长连续连续递增序列
* @param nums
* @return
*/
public int findLengthOfLCIS(int[] nums) {
int max = 1;
int temp = 1;
for(int i = 1;i < nums.length;i++){
if(nums[i] > nums[i - 1]){
temp++;
max = Math.max(max,temp);
}else{
temp = 1;
}
}
return max;
}
11.最长递增子序列的个数
这道题目和最长上升子序列问题很相似,但是这道题目要求记录最长上升子序列的组合模式
比如:
[1,3,5,4,7]中[1,3,5,7]和[1,3,4,7]都是最长的上升子序列,长度都为4,但是有两种组合模式
难点就在于记录组合数
所以我们用多一个dp数组来记录这个组合数
combination[i]:表示以索引i结尾的子数组的最大的最大上升子序列的组合数
combination[i]初始化都赋值为1,只要有数字,那么至少都是1。
分析状态转移:区间是[ i,j ]
if nums[i] <= nums[j]:
不是上升序列,直接跳过
else //nums[i] > nums[j]
if dp[j] + 1 == dp[j]
//则找到了长度和之前一样的上升子序列
combination[i] += combination[j]//更新以i结尾的组合数
else if dp[j] + 1 > dp[j]
//找到了更长的上升序列
dp[i] = dp[j] + 1//更新长度
combination[i] = combination[j];//更新以i结尾的组合数
参考图:https://leetcode-cn.com/problems/longest-consecutive-sequence/solution/tao-lu-jie-jue-zui-chang-zi-xu-lie-deng-yi-lei-wen/
/**
* 最长递增子序列数
* @param nums
* @return
*/
public int findNumberOfLIS(int[] nums) {
if (nums.length == 0) {
return 0;
}
int[] dp = new int[nums.length];
int[] combination = new int[nums.length];
Arrays.fill(dp, 1);
Arrays.fill(combination, 1);
int max = 1, res = 0;
for (int i = 1; i < dp.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (dp[j] + 1 > dp[i]) {
//找到了更长的上升序列
dp[i] = dp[j] + 1; //更新dp[i]长度
combination[i] = combination[j];//更新以i结尾的组合数
} else if (dp[j] + 1 == dp[i]) {
//找到了和之前存的最长序列长度一样的序列
combination[i] += combination[j];//更新组合数
}
}
}
max = Math.max(max, dp[i]);
}
//统计长度为最长上升序列长度的子序列组合数
for (int i = 0; i < nums.length; i++){
if (dp[i] == max){
res += combination[i];
}
}
return res;
}
12.最长连续序列
最长连续序列和最长连续递增序列相似,但是这道题元素和元素之间要求连续,即 1 ,2 ,3 ,4…
思路也和最长连续递增序列相似:
temp = 1;//记录长度
if nums[i] > nums[i - 1] + 1
temp++ //只有连续递增长度才会增加
else
temp = 1; //否则只能回到初始值,下一次循环
最长连续递增序列思路:
temp = 1;//记录长度
if nums[i] > nums[i - 1]
temp++ //只有连续递增长度才会增加
else
temp = 1; //否则只能回到初始值,下一次循环
实现
public int longestConsecutive1(int[] nums) {
if(nums.length == 0){
return 0;
}
int currentMax = 1;
int max = 0;
Arrays.sort(nums);
for(int i = 1;i < nums.length;i++){
if(nums[i] != nums[i - 1]){
if(nums[i] == nums[i - 1] + 1){
currentMax++;
}else{
max = Math.max(max,currentMax);
currentMax = 1;
}
}
}
return Math.max(currentMax,max);
}
13.最长和谐子序列
这道题目先统计所有元素的出现次数
//统计各个元素出现次数
for(int i : nums){
map.put(i,map.getOrDefault(i,0) + 1);
}
再遍历一次数组,以当前遍历到的元素为最小值,那么最大值则是 i+1,判断map中是否存在该元素,有则计算最大值和最小值的数量
/**
* 最长和谐子序列
* @param nums
* @return
*/
public int findLHS(int[] nums) {
if(nums.length == 0){
return 0;
}
Map<Integer,Integer> map = new HashMap<>();
//统计各个元素出现次数
for(int i : nums){
map.put(i,map.getOrDefault(i,0) + 1);
}
int max = 1;
int temp = 1;
for(int i : nums){
//以当前遍历元素为最小值,那么最大值则为i + 1,判断map中是否有该元素
if(map.containsKey(i + 1)){
temp = map.get(i) + map.get(i + 1);
max = Math.max(temp,max);
}
}
return max;
}
14.编辑距离
状态定义:
dp[i][j]:长度为i和j的两个字符串转换所需要的最少操作数
状态转移分析:
if s1[i] == s2[j]
dp[i][j] = dp[i - 1][j - 1]
else
dp[i][j] = min{
dp[i][j - 1]//插入一个字符
dp[i - 1][j]//删除一个字符
dp[i - 1][j - 1]//替换一个字符
}
java实现:
public int minDistance(String word1, String word2) {
int len1 = word1.length();
int len2 = word2.length();
int[][] dp = new int[len1+ 1][len2 + 1];
dp[0][0] = 0;
//如果任意一个字符串是空的都需要增加或删除跟字符串长度一样的字符数
for(int i = 1;i <= len1;i++){
dp[i][0] = i;
}
for(int i = 1;i <= len2;i++){
dp[0][i] = i;
}
for(int i = 1;i <= len1;i++){
for(int j = 1;j <= len2;j++){
if(word1.charAt(i - 1) == word2.charAt(j - 1)){
dp[i][j] = dp[i - 1][j - 1];
}else{
dp[i][j] = Math.min(Math.min(dp[i - 1][j],dp[i - 1][j - 1]),dp[i][j - 1]) + 1;
}
}
}
return dp[len1][len2];
}