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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章