300. Longest Increasing Subsequence

来源:互联网 发布:电陶炉和电磁炉 知乎 编辑:程序博客网 时间:2024/05/15 06:22

300. 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 is4. 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 logn) time complexity?

        这个题目要求找到最长递增子序列的长度,用动态规划很好解决,建立一个数组,储存到每个节点递增子序列的长度,对于每一个节点更新其后所有比它大的节点到此节点的最大距离,当所有节点更新完,找出最大值就是最长递增子序列的长度。

class Solution {public:    int lengthOfLIS(vector<int>& nums) {        int s = nums.size();        if(!s) return 0;    vector<int> L(s);    int Max = 1;    for (int i = 0; i < s - 1; i++) {    if (L[i] == 0) L[i]=1;    for (int j = i + 1; j < s; j++) {    if (nums[i]<nums[j]&&L[j] < L[i] + 1) L[j] = L[i] + 1;    if (Max < L[j]) Max = L[j];    }    }    return Max;    }};

0 0
原创粉丝点击