题目描述:
Given an unsorted array of integers, find the length of longest increasing subsequence.
Example:
Input:[10,9,2,5,3,7,101,18]
Output: 4 Explanation: The longest increasing subsequence is[2,3,7,101]
, therefore the length is4
.
Note:
- There may be more than one LIS combination, it is only necessary for you to return the length.
- Your algorithm should run in O(n2) complexity.
Follow up: Could you improve it to O(n log n) time complexity?
解题思路:
这道题目可以用动态规划来解:
dp[i]表示比在此之前比nums[i]小的数字的个数
dp[0] = 0;
需要通过for 循环来找可能比i小的数字
for(int j = i-1; j > -1; j++){
if(nums[j] < nums[i]){
dp[i] = max(dp[i], dp[j]+1);
}
}
注意dp中存的是比nums[i]小的数字,所以我们最后的返回值是需要+1的
而且我们需要用一个max 来记录最大的值。
代码:
class Solution { public: int lengthOfLIS(vector<int>& nums) { if(nums.empty()) return 0; int n = nums.size(); vector<int> dp(n, 0); dp[0] = 0; int ret = 0; for(int i = 1; i < n; i++){ int pre = 0; for(int j = i-1; j > -1; j--){ if(nums[j] < nums[i]){ pre = max(pre, dp[j]+1); } } dp[i] = pre; ret = max(dp[i], ret); } return ret+1; } };
动态规划的时间复杂度为O(n2)
这道题的follow up是时间复杂度为O(nlogn)
看到logn和数组会莫名联想到二分搜索。
但是我还没有看明白这个解法。