Leetcode 300.longest-increasing-subsequence

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

  1. dp[i]代表以第i个数结尾的XXX
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值