我正在解决问题https://www.hackerearth.com/problem/algorithm/mancunian-and-k-ordered-lcs-e6a4b8c6/,并在观看了一个教学视频,他们使用3d DP方法。但是代码在Java中赋予了TLE。 这是代码
import java.util.*;
class TestClass {
public static int find(int a[], int b[], int n, int m, int k, int i, int j, int dp[][][]) {
int ans = 0;
if (i == n || j == m) return 0;
if (dp[i][j][k] != -1) return dp[i][j][k];
if (a[i] == b[j])
ans = 1 + find(a, b, n, m, k, i + 1, j + 1, dp);
else {
if (k > 0)
ans = 1 + find(a, b, n, m, k - 1, i + 1, j + 1, dp);
int q1 = find(a, b, n, m, k, i, j + 1, dp);
int q2 = find(a, b, n, m, k, i + 1, j, dp);
ans = Math.max(ans, Math.max(q1, q2));
}
dp[i][j][k] = ans;
return ans;
}
public static void main(String args[]) throws Exception {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int m = s.nextInt();
int k = s.nextInt();
int a[] = new int[n];
int b[] = new int[m];
for (int i = 0; i < n; i++)
a[i] = s.nextInt();
for (int i = 0; i < m; i++)
b[i] = s.nextInt();
int dp[][][] = new int[n + 1][m + 1][k + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= m; j++) {
for (int z = 0; z <= k; z++) {
dp[i][j][z] = -1;
}
}
}
System.out.println(find(a, b, n, m, k, 0, 0, dp));
}
}
有人可以帮助解决该问题吗?