method 1 dp
使用动态规划,dp[i]代表以第i个数结尾时的最大长度
//dp[i]表示以num[i]结尾的序列的最大长度
int lengthOfLIS(vector<int>& nums) {
if (nums.size() == 0) return 0;
vector<int> dp(nums.size(), 1);
for (int i = 1; i < nums.size(); i++)
{
for (int j = 0; j < i; j++)
{
if (nums[i] > nums[j]){
dp[i] = max(dp[j] + 1, dp[i]);
}
}
}
int ans = 0;
for (int n : dp) ans = max(n, ans);
return ans;
}
method 2 binary search
与自己一开始想的binary search不一样,这个并不是range下的binary search,仍然是scope,只是在dp上scope而不是在nums上scope
虽然tag有bs,但重点还是dp,此时的dp与上一个dp不一样,dp中保存的是一个上升序列,遍历nums,将nums[i]插入dp中合适的位置,最后dp的size()就是answer
//找最长上升序列,可以借用一个数组来找,在数组中找到其合适的位置
//https://leetcode.com/problems/longest-increasing-subsequence/discuss/74897/Fast-Java-Binary-Search-Solution-with-detailed-explanation
int lengthOfLIS2(vector<int>& nums) {
if (nums.empty()) { return 0; }
vector<int> tail; // keep tail value of each possible len
tail.push_back(nums[0]);
for (auto n : nums) {
if (n <= tail[0]) {
tail[0] = n;
}
else if (n > tail.back()) { // large than the tail of current largest len
tail.push_back(n);
}
else { // find smallest one which is >= n
int left = 0;
int right = tail.size() - 1;
int res = left;
while (left <= right) {
int mid = left + (right - left) / 2;
if (tail[mid] >= n) {
res = mid;
right = mid - 1;
}
else { // tail[mid] < n
left = mid + 1;
}
}
tail[res] = n;
}
}
return tail.size();
}
summary
- dp[i]代表以第i个数结尾的XXX