-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLongestSubSequence.java
93 lines (67 loc) · 2.12 KB
/
LongestSubSequence.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import java.util.Arrays;
/*
Longest Increasing Subsequence
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input: [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.
Note:
There may be more than one LIS combination, it is only necessary for you to return the length.
Your algorithm should run in O(n2) complexity.
*/
public class LongestSubSequence {
public static int lengthOfLIS(int[] nums) {
int n=nums.length;
int[] dp=new int[n];
Arrays.fill(dp,1);
int lis=1;
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(nums[j]<nums[i]){
dp[i]=Math.max(dp[i],dp[j]+1);
}
}
lis=Math.max(lis,dp[i]);
}
return lis;
}
public static int findNumberOfLIS(int[] nums) {
if (nums.length == 0)
return 0;
int n = nums.length;
int[] length = new int[n], count = new int[n];
Arrays.fill(length, 1);
Arrays.fill(count, 1);
int lis = 1;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (length[j] + 1 > length[i]) {
length[i] = length[j] + 1;
count[i] = count[j];
} else if (length[j] + 1 == length[i]) {
count[i] += count[j];
}
}
}
lis = Math.max(lis, length[i]);
}
int numLis = 0;
for (int i = 0; i < n; i++)
if (length[i] == lis)
numLis += count[i];
return numLis;
}
public static void main(String[] args) {
/*
Finding Length of longest increasing subsequence
int[] arr={10,9,2,5,3,7,101,18};
int res = lengthOfLIS(arr);
System.out.println(res);
*/
int[] nums = {1,3,5,4,7};
int numberOfLIS = findNumberOfLIS(nums);
System.out.println(numberOfLIS);
}
}