-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path1_Longest_increasing_subsequence.cpp
108 lines (75 loc) · 2.17 KB
/
1_Longest_increasing_subsequence.cpp
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// https://leetcode.com/problems/longest-increasing-subsequence/submissions/
// Simple recursive approach
class Solution {
public:
int solve(vector<int>& nums,int ind,int last){
// base case
if(ind==nums.size()){
return 0;
}
int incl = 0;
if(last == -1 || nums[ind]>last){
incl = 1 + solve(nums,ind+1,nums[ind]);
}
int excl = solve(nums,ind+1,last);
int ans = max(incl,excl);
return ans;
}
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
return solve(nums,0,-1);
}
};
// Top down : recursive + memoization
// time : O(N2)
// space : O(N2)
class Solution {
public:
int solve(int n,vector<int>& nums,int ind,int last, vector<vector<int> > &dp){
// base case
if(ind==n){
return 0;
}
if(dp[ind][last+1] != -1){
return dp[ind][last+1];
}
int incl = 0;
if(last == -1 || nums[ind]>nums[last]){
incl = 1 + solve(n,nums,ind+1,ind,dp);
}
int excl = solve(n,nums,ind+1,last,dp);
return dp[ind][last+1] = max(incl,excl);
}
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<vector<int> > dp(n+1,vector<int> (n+1,-1));
return solve(n,nums,0,-1,dp);
}
};
// Bottom up : Tabulation
// time : O(N2)
// space : O(N2)
class Solution {
public:
int solve(vector<int>& nums){
int n = nums.size();
vector<vector<int> > dp(n+1,vector<int> (n+1,0));
for(int i = n-1;i>=0;i--){
for(int j=i-1;j>=-1;j--){
int incl = 0;
if(j == -1 || nums[i]>nums[j]){
incl = 1 + dp[i+1][i+1];
}
int excl = dp[i+1][j+1];
dp[i][j+1] = max(incl,excl);
}
}
return dp[0][0];
}
int lengthOfLIS(vector<int>& nums) {
return solve(nums);
}
};
// space optimization
// time : O(N2)
// space : O(N2)