LeetCode 300. Longest Increasing Subsequence

来源:互联网 发布:qq邮箱smtp设置 端口25 编辑:程序博客网 时间:2024/06/11 11:57

一、问题描述

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.
对于一个无序的数组,找出其中的最长递增子序列的长度

二、解题思路

这是一个动态规划问题,通过局部最优解可以推出全局最优解。
维护一个与原数组等长的数组(记该数组为v),记录对于数组中的每一个元素n,由n和它之前的所有数组成一个序列,若以n为最后一个元素,能构成的最长递增序列的长度。v[i]的数值由v[j](j小于i)决定,对于n前面的数,找到一个同时满足数值小于n且 v[j]最小的,则v[i]=v[j]+1。最后返回数组v中的最大值

三、C++代码

class Solution {public:    int lengthOfLIS(vector<int>& nums) {        vector<int> v;        if (nums.empty()) {            return 0;        }        v.push_back(1);        int count = 0;        for (int i = 0; i < nums.size(); i++) {           for (int j = 0; j < i; j++) {               if (nums[j] < nums[i] && v[j] >= count) {                   count = v[j];               }           }            if (i != 0)            v.push_back(count+1);            count = 0;        }        sort(v.begin(), v.end());        return v[v.size()-1];    }};
阅读全文
0 0
原创粉丝点击