import
java.util.ArrayList;
import
java.util.HashSet;
import
java.util.List;
import
java.util.Set;
import
java.util.Arrays;
import
java.util.Collections;
public
class
LCIS {
public
static
List<Integer> lcis(List<Integer> arr1, List<Integer> arr2) {
List<Integer> lcis =
new
ArrayList<>();
int
lcisLength =
0
;
for
(
int
i =
1
; i <= Math.min(arr1.size(), arr2.size()); i++) {
List<List<Integer>> combinations1 = generateCombinations(arr1, i);
for
(List<Integer> seq1 : combinations1) {
if
(!isSorted(seq1)) {
continue
;
}
List<List<Integer>> combinations2 = generateCombinations(arr2, i);
for
(List<Integer> seq2 : combinations2) {
if
(!isSorted(seq2)) {
continue
;
}
if
(hasSameElements(seq1, seq2)) {
lcisLength = i;
lcis = seq1;
}
}
}
}
return
lcis;
}
public
static
List<List<Integer>> generateCombinations(List<Integer> arr,
int
k) {
List<List<Integer>> combinations =
new
ArrayList<>();
generateCombinationsHelper(arr, k,
0
,
new
ArrayList<>(), combinations);
return
combinations;
}
public
static
void
generateCombinationsHelper(List<Integer> arr,
int
k,
int
startIndex, List<Integer> current, List<List<Integer>> combinations) {
if
(k ==
0
) {
combinations.add(
new
ArrayList<>(current));
return
;
}
for
(
int
i = startIndex; i < arr.size(); i++) {
current.add(arr.get(i));
generateCombinationsHelper(arr, k -
1
, i +
1
, current, combinations);
current.remove(current.size() -
1
);
}
}
public
static
boolean
isSorted(List<Integer> arr) {
List<Integer> sortedArr =
new
ArrayList<>(arr);
Collections.sort(sortedArr);
return
arr.equals(sortedArr);
}
public
static
boolean
hasSameElements(List<Integer> arr1, List<Integer> arr2) {
Set<Integer> set1 =
new
HashSet<>(arr1);
Set<Integer> set2 =
new
HashSet<>(arr2);
return
set1.equals(set2);
}
public
static
void
main(String[] args) {
List<Integer> arr1 = Arrays.asList(
3
,
4
,
9
,
1
);
List<Integer> arr2 = Arrays.asList(
5
,
3
,
8
,
9
,
10
,
2
,
1
);
List<Integer> result = lcis(arr1, arr2);
System.out.println(
"Longest Common Increasing Subsequence: "
+ result);
System.out.println(
"Length of LCIS: "
+ result.size());
}
}