Title description: given an unordered integer array, the length of the longest found rising sequence.
Example:
输入: [10,9,2,5,3,7,101,18]
输出: 4
解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4。
ALGORITHM: Title rise longest sequence requirements, need to set up a DP [] array for recording the final result length, dp [i] is the last element contains the sequence nums [i] of length. dp [i] values are only two cases, the first case: the current surface element are not currently nums [i] value of the element is small, dp [i] = 1, i.e., contains only elements themselves, the length is 1. Second case: Present surface of the small element ratio nums [i], the current will nums [i] is added to the back of the element is smaller than nums [i], dp [i ] = dp [i] +1.
Specifically: initializing the array dp, dp [i] = 1, ans = -1 is used to return the maximum length increment, when nums [i]> when nums [j], and dp [i] <dp [j ] +1 when , updated dp [i] = dp [j ] +1, DP calculate a [i], to update the look ans, ans = max (ans, dp [i]), the maximum final ans is increasing subsequence length
i
Code:
class Solution {
public:
int lengthOfLIS(vector<int>& nums) {
int length=nums.size();
if(length==0)
return 0;
int dp[length];
for(int i=0;i<length;i++){
dp[i]=1;//边界
}
int ans=-1;
for(int i=0;i<length;i++){
for(int j=0;j<i;j++){
if(nums[i]>nums[j]&&(dp[i]<dp[j]+1)){
dp[i]=dp[j]+1;
}
}
ans=max(ans,dp[i]);
}
return ans;
}
};