这题我做的时候用了动态规划,但是也只是能满足时间复杂度小于O(N2),先看下题目

Given an unsorted array of integers, find the length of longest increasing subsequence.

Example:

Input: [10,9,2,5,3,7,101,18]
Output: 4 
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4. 

Note:

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?

这题一看就感觉是用动态规划做的,递推公式也比较简单,我们分别算出以n为结束点的子串的最大连续增长数,那么下一个n-1位置的值就是扫描前面[0,n]位置的值,假设n的值大于其中的值,那么就把那个点的dp值加1,然后找到最大的dp值,最后把当前位置的dp值给更新掉,如此n位置的dp值就可以得到了。然后我们再维护一个全局的最大递增子串长度值,用每个n位置的dp值去比较。思路其实不难,下面贴代码:

int lengthOfLIS(vector<int>& nums) {
    if (nums.empty()) {
        return 0;
    }
    vector<int> dps(nums.size(), 1);
    int res = 1;
    for (int i = 0; i < nums.size(); ++i) {
        int mx = 0;
        for (int j = 0; j < i; ++j) {
            if (nums[i] > nums[j]) {
                if (dps[j] > mx) {
                    mx = dps[j];
                }
            }
            dps[i] = mx + 1;
            if (dps[i] > res) {
                res = dps[i];
            }
        }
    }
    return res;
}
共 0 条回复
暂时没有人回复哦,赶紧抢沙发
发表新回复

作者

sryan
today is a good day