Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static List<Integer> longestCommonSubsequence(List<Integer> a, List<Integer> b) {
- List<Integer> ans = new ArrayList<>();
- int m = a.size() + 1;
- int n = b.size() + 1;
- int[][] arr = new int[m][n];
- if (a.size() < 0 || b.size() < 0) {
- return ans;
- }
- for (int i = 1; i <= m - 1; i++) {
- for (int j = 1; j <= n - 1; j++) {
- if (a.get(i - 1) != null && b.get(j - 1) != null && a.get(i - 1) == b.get(j - 1)) {
- arr[i][j] = arr[i - 1][j - 1] + 1;
- } else {
- arr[i][j] = Math.max(arr[i - 1][j], arr[i][j - 1]);
- }
- }
- }
- int i = a.size();
- int j = b.size();
- while (i > 0 && j > 0) {
- if (a.get(i - 1) != null && b.get(j - 1) != null && a.get(i - 1) == b.get(j - 1)) {
- ans.add(a.get(i - 1));
- i--;
- j--;
- } else if (arr[i][j] == arr[i][j - 1]) {
- j--;
- } else {
- i--;
- }
- }
- Collections.reverse(ans);
- return ans;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement