动态规划 判断子序列 java 动态规划状态压缩

This commit is contained in:
yangzhaoMP
2024-03-06 16:03:39 +08:00
parent 1474a28a53
commit 58595806a0

View File

@ -173,6 +173,63 @@ class Solution {
} }
} }
``` ```
> 修改遍历顺序后可以利用滚动数组对dp数组进行压缩
```java
class Solution {
public boolean isSubsequence(String s, String t) {
// 修改遍历顺序外圈遍历t内圈遍历s。使得dp的推算只依赖正上方和左上方方便压缩。
int[][] dp = new int[t.length() + 1][s.length() + 1];
for (int i = 1; i < dp.length; i++) { // 遍历t字符串
for (int j = 1; j < dp[i].length; j++) { // 遍历s字符串
if (t.charAt(i - 1) == s.charAt(j - 1)) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = dp[i - 1][j];
}
}
System.out.println(Arrays.toString(dp[i]));
}
return dp[t.length()][s.length()] == s.length();
}
}
```
> 状态压缩
```java
class Solution {
public boolean isSubsequence(String s, String t) {
int[] dp = new int[s.length() + 1];
for (int i = 0; i < t.length(); i ++) {
// 需要使用上一轮的dp[j - 1],所以使用倒序遍历
for (int j = dp.length - 1; j > 0; j --) {
// i遍历的是t字符串j遍历的是dp数组dp数组的长度比s的大1因此需要减1。
if (t.charAt(i) == s.charAt(j - 1)) {
dp[j] = dp[j - 1] + 1;
}
}
}
return dp[s.length()] == s.length();
}
}
```
> 将dp定义为boolean类型dp[i]直接表示s.substring(0, i)是否为t的子序列
```java
class Solution {
public boolean isSubsequence(String s, String t) {
boolean[] dp = new boolean[s.length() + 1];
// 表示 “” 是t的子序列
dp[0] = true;
for (int i = 0; i < t.length(); i ++) {
for (int j = dp.length - 1; j > 0; j --) {
if (t.charAt(i) == s.charAt(j - 1)) {
dp[j] = dp[j - 1];
}
}
}
return dp[dp.length - 1];
}
}
```
### Python ### Python