forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
longest-increasing-subsequence.cpp
87 lines (75 loc) · 2.06 KB
/
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
// Time: O(nlogn)
// Space: O(n)
// Binary search solution with STL.
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> LIS;
for (const auto& num : nums) {
insert(&LIS, num);
}
return LIS.size();
}
private:
void insert(vector<int> *LIS, const int target) {
// Find the first index "left" which satisfies LIS[left] >= target
auto it = lower_bound(LIS->begin(), LIS->end(), target);
// If not found, append the target.
if (it == LIS->end()) {
LIS->emplace_back(target);
} else {
*it = target;
}
}
};
// Binary search solution.
class Solution2 {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> LIS;
for (const auto& num : nums) {
insert(&LIS, num);
}
return LIS.size();
}
private:
void insert(vector<int> *LIS, const int target) {
int left = 0, right = LIS->size() - 1;
auto comp = [](int x, int target) { return x >= target; };
// Find the first index "left" which satisfies LIS[left] >= target
while (left <= right) {
int mid = left + (right - left) / 2;
if (comp((*LIS)[mid], target)) {
right = mid - 1;
} else {
left = mid + 1;
}
}
// If not found, append the target.
if (left == LIS->size()) {
LIS->emplace_back(target);
} else {
(*LIS)[left] = target;
}
}
};
// Time: O(n^2)
// Space: O(n)
// Traditional DP solution.
class Solution3 {
public:
int lengthOfLIS(vector<int>& nums) {
const int n = nums.size();
vector<int> dp(n, 1); // dp[i]: the length of LIS ends with nums[i]
int res = 0;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
dp[i] = max(dp[i], dp[j] + 1);
}
}
res = max(res, dp[i]);
}
return res;
}
};