动态规划 —— 最长上升子序列

给定一个无序的整数数组,找到其中最长上升子序列的长度。题目传送门

示例:

输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。

简单的dp,状态转移方程,时间复杂度O(n^2)

dp[i] = max(dp[i],dp[j]+1)

class Solution {
     
public:
	int lengthOfLIS(vector<int>& nums) {
     
		const int n = nums.size();
		vector<int> dp(n, 1);
		int result = 0;
		for (int i = 0; i < n; i++)
		{
     
			for (int j = 0; j < i; j++)
			{
     
				if (nums[i] > nums[j])
				{
     
					dp[i] = max(dp[i], dp[j] + 1);
				}
			}
			result = max(result, dp[i]);
		}
		return result;
	}
};

贪心+二分查找

class Solution {
     
public:
	int lengthOfLIS(vector<int>& nums) {
     
		int len = 1;
		const int n = static_cast<int>(nums.size());
		if (n == 0) return 0;
		vector<int> d(n + 1, 0);
		d[len] = nums[0];
		for (int i = 1; i < n; ++i) {
     
			if (nums[i] > d[len]) d[++len] = nums[i];
			else {
     
				int l = 1, r = len, pos = 0;
				while (l <= r) {
     
					int mid = (l + r) >> 1;
					if (d[mid] < nums[i]) {
     
						pos = mid;
						l = mid + 1;
					}
					else {
     
						r = mid - 1;
					}	
				}
				d[pos + 1] = nums[i];
			}
		}
		return len;
	}
};

你可能感兴趣的:(LeetCode)