-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy path300. Longest Increasing Subsequence
83 lines (58 loc) · 1.88 KB
/
300. Longest Increasing Subsequence
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
//Recursion - Brute force (TLE)
class Solution {
public int lengthOfLIS(int[] nums) {
if(nums.length <= 1) return nums.length;
return lis(nums, 0, -1);
}
private int lis(int[] nums, int currentInd, int prevInd) {
if(currentInd == nums.length) return 0;
int skip = lis(nums, currentInd + 1, prevInd);
int select = -1;
if(prevInd == -1 || nums[currentInd] > nums[prevInd]) {
select = 1 + lis(nums, currentInd+1, currentInd);
}
return Math.max(skip, select);
}
}
//Recursion + Memoization
class Solution {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
if(n <= 1) return n;
int[][] dp = new int[n][n+1];
for(int[] rows : dp) {
Arrays.fill(rows, -1);
}
return lis(nums, 0, -1, dp);
}
private int lis(int[] nums, int currentInd, int prevInd, int[][] dp) {
if(currentInd == nums.length) return 0;
if(dp[currentInd][prevInd+1] != -1) return dp[currentInd][prevInd+1];
int skip = lis(nums, currentInd + 1, prevInd, dp);
int select = -1;
if(prevInd == -1 || nums[currentInd] > nums[prevInd]) {
select = 1 + lis(nums, currentInd+1, currentInd, dp);
}
dp[currentInd][prevInd+1] = Math.max(skip, select);
return dp[currentInd][prevInd+1];
}
}
//DP
class Solution {
public int lengthOfLIS(int[] nums) {
int n = nums.length;
if(n <= 1) return n;
int[] dp = new int[n];
Arrays.fill(dp, 1);
int maxLength = 0;
for(int i = 1; i < n; i++) {
for(int j = 0; j < i; j++) {
if(nums[i] > nums[j]) {
dp[i] = Math.max(dp[i], 1+dp[j]);
}
}
maxLength = Math.max(maxLength, dp[i]);
}
return maxLength;
}
}