LeetCode 300. Longest Increasing Subsequence 题解

来源:互联网 发布:现货模拟软件 编辑:程序博客网 时间:2024/06/06 14:27

300. Longest Increasing Subsequence

 
 My Submissions
  • Total Accepted: 55308
  • Total Submissions: 149684
  • Difficulty: Medium
  • Contributors: Admin

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?




解题思路:

令数组为a[n]。

设以数组中第i个数为结尾的最长上升子序列的长度为d[i]。则d[i]=max(d[j]+1),(0<=j<i&&a[j]<a[i])。

代码展示:

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


0 0
原创粉丝点击