leetcode--Longest Increasing Subsequence

来源:互联网 发布:类似于prisma的软件 编辑:程序博客网 时间:2024/05/22 13:44

1.题目

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.

2.分析

这是典型的动态规划类型题。用curMinLen[i]保存前i个元素的最长子序列长度,且状态转移方程为curMinLen[i] = max{curMinLen[j]+1},0<=j<i,即取当前元素之前且比当前元素小的元素中的最长长度+1。


3.实现

class Solution {public:    int lengthOfLIS(vector<int>& nums) {        const int size = nums.size();        vector<int> curMinLen(size,1);        if(0 == size) return 0;        int res = 1;        for(int i=1; i<size; ++i) {            for(int j=0; j<i; ++j) {                if(nums[j] < nums[i])                    curMinLen[i] = max(curMinLen[i],curMinLen[j]+1);            }            res = max(res,curMinLen[i]);        }        return res;    }};


1 0
原创粉丝点击