java
复制代码
class Solution {
public int findLength(int[] nums1, int[] nums2) {
int max = 0;
int[][] dp = new int[nums1.length][nums2.length];
for (int i = 0; i < nums1.length; i++) {
for (int j = 0; j < nums2.length; j++) {
if (nums1[i] == nums2[j]) {
if (i == 0 || j == 0) {
dp[i][j] = 1;
} else {
dp[i][j] = dp[i - 1][j - 1] + 1;
}
if (dp[i][j] > max) {
max = dp[i][j];
}
}
}
}
// for (int[] ints : dp) {
// System.out.println(Arrays.toString(ints));
// }
return max;
}
}
java
复制代码
class Solution {
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
dp[i] = Integer.max(dp[i], dp[j] + 1);
if (dp[i] > max) {
max = dp[i];
}
}
}
}
return max;
}
}
java
复制代码
class Solution {
public int findLengthOfLCIS(int[] nums) {
int[] dp = new int[nums.length];
Arrays.fill(dp, 1);
int max = 1;
for (int i = 1; i < nums.length; i++) {
if (nums[i - 1] < nums[i]) {
dp[i] = dp[i - 1] + 1;
if (dp[i] > max) {
max = dp[i];
}
}
}
// System.out.println(Arrays.toString(dp));
return max;
}
}
java
复制代码
class Solution {
public int longestCommonSubsequence(String text1, String text2) {
int[][] dp = new int[text1.length() + 1][text2.length() + 1];
char[] chars1 = text1.toCharArray();
char[] chars2 = text2.toCharArray();
for (int i = 1; i < chars1.length + 1; i++) {
for (int j = 1; j < chars2.length + 1; j++) {
if (chars1[i - 1] == chars2[j - 1]) {
dp[i][j] = dp[i - 1][j - 1] + 1;
} else {
dp[i][j] = Integer.max(dp[i - 1][j], dp[i][j - 1]);
}
}
}
return dp[chars1.length][chars2.length];
}
}