LeetCode OJ:Longest Increasing Subsequence(最长递增序列)
Given an unsorted array of integers, find the length of longest increasing subsequence.
For example,
Given [10, 9, 2, 5, 3, 7, 101, 18]
,
The longest increasing subsequence is [2, 3, 7, 101]
, therefore the length is 4
. Note that 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解决,注意这里的递增序列不是指连续的递增 ,可以是不连续的, 代码如下:
1 class Solution { 2 public: 3 int lengthOfLIS(vector<int>& nums) { 4 if(nums.size() <= 1) return nums.size(); 5 vector<int> dp(nums.size(), 0); 6 int maxVal = 1; 7 for(int i = 0; i < nums.size(); ++i){ 8 dp[i] = 1; 9 for(int j = 0; j < i; ++j){ 10 if(nums[j] < nums[i]){ 11 dp[i] = max(dp[i], dp[j]+1); 12 maxVal = max(dp[i], maxVal); 13 } 14 } 15 } 16 return maxVal; 17 } 18 };