这星期老师刚好讲到动态规划,讲了最长递增子序列(LIS)问题,于是在LeetCode中找了该题来做
1 题目
求最长递增子序列长度。即在一个给定的数值序列中,找到一个子序列,使得这个子序列元素的数值依次递增,并且这个子序列的长度尽可能地大。最长递增子序列中的元素在原序列中不一定是连续的。这是一道动态规划的典型问题
点击打开链接
2 分析
该题利用动态规划的方法,有两种常用的方法:
该题利用动态规划的方法,有两种常用的方法:
方法一:
O(n^2)复杂度
O(n^2)复杂度
用一个数组dp[i]存储以当前位置的数字结尾(nums[i])的最长递增子序列的长度
dp(i) = max {L(j), j<i && nums[i] > nums[j] } + 1
int Max(int a, int b) {
return a > b ? a : b;
}
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
if(nums.empty()) return 0;
if(nums.size() == 1) return 1;
int n = nums.size();
vector<int> dp(n, 1);
int res = 1;
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);
}
res = Max(dp[i], res);
}
return res;
}
};
方法二:
O(nlogn)复杂度
O(nlogn)复杂度
用一个数组minEnd[i]存储长度为i+1的递增子序列的最小末尾数,则minEnd数组是有序的。
对于每一个nums[i],在minEnd中找到第一各比nums[i]大的数所在的位置pos,并且用nums[i]替换minEnd[pos]
最后minEnd数组中的元素个数即为所求的最大长度
note:
因为minEnd是有序的,使用二分查找的方法进行查找并替换,复杂度为logn
minEnd中的序列并不是要求的递增子序列
class Solution {
public:
/**
* 输入:有序数组nums,要查找的数target
* 返回:第一个比target大的数的位置
**/
int search(int start, int end, int target, vector<int> nums) {
if (target > nums[end])
return end + 1;
else if(target < nums[start])
return start;
else {
int mid = (start + end) / 2;
//target已经存在于数组中
if(target == nums[mid])
return -1;
else if(target < nums[mid])
return search(start, mid, target, nums);
else if(target > nums[mid])
return search(mid + 1, end, target, nums);
}
}
int lengthOfLIS(vector<int>& nums) {
//数组为空,LIS长度为0
if(nums.empty())
return 0;
//数组长度为1时,LIS长度为1
if(nums.size() == 1)
return 1;
//minEnd[i]:存储长度为i+1的递增子序列的最小末尾数
vector<int> minEnd(nums.size());
minEnd[0] = nums[0];
//minEnd的元素个数
int len = 1;
for(int i = 1; i < nums.size(); i++) {
int pos = search(0, len - 1, nums[i], minEnd);
if(pos == -1)
continue;
else {
minEnd[pos] = nums[i];
if(pos == len)
len++;
}
}
return len;
}
};