修复了LeetCode300和LeetCode115的测试代码,优化了提交信息格式。

This commit is contained in:
whaifree 2024-04-30 12:55:51 +08:00
parent d5e3175b11
commit 121028b955
2 changed files with 117 additions and 0 deletions

View File

@ -0,0 +1,65 @@
package cn.whaifree.redo.redo_24_4_27;
import org.junit.Test;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/4/30 11:20
* @注释
*/
public class LeetCode115 {
@Test
public void test() {
String s = "babgbag";
String t = "bag";
System.out.println(new Solution().numDistinct(s, t));
}
class Solution {
/**
* 给你两个字符串 s t 统计并返回在 s 子序列 t 出现的个数结果需要对 109 + 7 取模
* @param s
* @param t
* @return
*/
public int numDistinct(String s, String t) {
/**
*
* dp[i][j] 表示0-j在0-i子序列中出现的次数
* '' b a b g b a g
*'' 1 1 1 1 1 1 1 1
* b 0 1 1 2 2 3 3 3
* a 0 0 1 1 1 1 4 4
* g 0 0 0 0 1 1 1 5
*
* if s[i] == t[j]
* dp[i][j] =
* +
* - s使用i-1个位置 dp[i-1][j-1]
* - s不使用i-1个位置 dp[i][j-1]
* else
* dp[i][j-1]
*/
int lenS = s.length();
int lenT = t.length();
int[][] dp = new int[lenT + 1][lenS + 1];
for (int i = 0; i <= lenS; i++) {
dp[0][i] = 1;
}
for (int j = 1; j <= lenT; j++) {
for (int i = 1; i <= lenS; i++) {
if (s.charAt(i - 1) == t.charAt(j - 1)) {
dp[j][i] = dp[j - 1][i - 1] + dp[j][i - 1];
} else {
dp[j][i] = dp[j][i - 1];
}
}
}
return dp[lenT][lenS];
}
}
}

View File

@ -0,0 +1,52 @@
package cn.whaifree.redo.redo_24_4_27;
import org.junit.Test;
import java.util.Arrays;
/**
* @version 1.0
* @Author whai文海
* @Date 2024/4/30 11:49
* @注释
*/
public class LeetCode300 {
@Test
public void test()
{
Solution solution = new Solution();
int[] nums = new int[]{10, 9, 2, 5, 3, 7, 101, 18};
int res = solution.lengthOfLIS(nums);
System.out.println(res);
}
class Solution {
/**
* 最长严格递增子序列的长度
*
* dp[i]表示以i为结尾的最长递增子序列的长度 计算i的时候0~(i-1)已经满足最长递增子序列的长度
*
*
* if (nums[j] < nums[i])
* dp[i] = dp[j] + 1
* dp[j] = dp[i]
*
* @param nums
* @return
*/
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int res = 1;
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
res = Math.max(res, dp[i]);
}
return res;
}
}
}