文章目录
problem
300. Longest Increasing Subsequence
Given an integer array nums, return the length of the longest strictly increasing subsequence.
A subsequence is a sequence that can be derived from an array by deleting some or no elements without changing the order of the remaining elements. For example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
Example 1:
Input: nums = [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.
Example 2:
Input: nums = [0,1,0,3,2,3]
Output: 4
Example 3:
Input: nums = [7,7,7,7,7,7,7]
Output: 1
approach 1 DP
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n, 1);
for(int i=0; i<n; i++){
for(int j=0; j<i; j++){
if(nums[j] < nums[i] && dp[i] < dp[j]+1)
dp[i] = dp[j] + 1;
}
}
return *max_element(dp.begin(), dp.end());
}
};
time complexity
:
O
(
n
(
n
−
1
)
2
)
=
O
(
n
2
)
O(\frac{n(n-1)}{2})=O(n^2)
O(2n(n−1))=O(n2)
space complexity
:
O
(
n
)
O(n)
O(n)
so the dynamic programming is not the best solution
approach 2 Greedy with Binary search
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
vector<int> sub;
sub.push_back(nums[0]);
for(int x : nums){
if(x > sub[sub.size()-1])
sub.push_back(x);
else{
auto it = lower_bound(sub.begin(), sub.end(), x);
*it = x;
}
}
return sub.size();
}
};
time complexity
:
O
(
n
∗
l
o
g
(
n
)
)
=
O
(
n
l
o
g
n
)
O(n*log(n))=O(nlogn)
O(n∗log(n))=O(nlogn) ,
O
(
l
o
g
n
)
O(logn)
O(logn) is the complexity of binary search
space complexity
:
O
(
n
)
O(n)
O(n)
approach 3 Binary Indexed Tree
others approach
class MaxBIT { // One-based indexing
vector<int> bit;
public:
MaxBIT(int size) {
bit.resize(size + 1);
}
int get(int idx) {
int ans = 0;
for (; idx > 0; idx -= idx & -idx)
ans = max(ans, bit[idx]);
return ans;
}
void update(int idx, int val) {
for (; idx < bit.size(); idx += idx & -idx)
bit[idx] = max(bit[idx], val);
}
};
class Solution { // 16 ms, faster than 72.16%
public:
int lengthOfLIS(vector<int>& nums) {
int BASE = 10001;
MaxBIT bit(20001);
for (int x : nums) {
int subLongest = bit.get(BASE + x - 1);
bit.update(BASE + x, subLongest + 1);
}
return bit.get(20001);
}
};
it isn’t a good approach