300. Longest Increasing Subsequence

来源:互联网 发布:手机乐器演奏软件 编辑:程序博客网 时间:2024/06/09 16:06

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?
Analysis:
之前做过,感觉挺经典的一道题。参考:http://blog.csdn.net/nnnnnnnnnnnny/article/details/51623145
Source Code(C++):

#include <iostream>#include <vector>#include <algorithm>using namespace std;class Solution {public:    int lengthOfLIS(vector<int>& nums) {        if (nums.empty()){            return 0;        }        int len_nums=nums.size();        vector<int> dp(len_nums, 1);        for(int i=0; i<len_nums; i++)            for (int j=0; j<i; j++) {                if (nums.at(i)>nums.at(j)) {                    dp.at(i)=max(dp.at(i), dp.at(j)+1);                }            }        return *max_element(dp.begin(), dp.end());    }};int main() {    Solution sol;    vector<int> v;    v.push_back(10);v.push_back(9);v.push_back(2);v.push_back(5);    v.push_back(3);v.push_back(7);v.push_back(101);v.push_back(18);    cout << sol.lengthOfLIS(v);    return 0;}
0 0
原创粉丝点击