Leetcode Longest Increasing Subsequences

題目描述

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.

解題思路

該題使用DP思想,可以將第k個元素的遞增序列長度動態算出。當第k個元素的值大於前k中任意一個元素時,將前k中元素的遞增序列長度+1,並取最長的一個長度保存至length[k]中作爲當前包含第k個元素的最長遞增序列長度。該思想的時間複雜度爲O(n2)

class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.empty())   return 0;
        int m = 0, length[nums.size()];
        memset(length, 0, sizeof(length));
        for (int i = 0; i < nums.size(); i++) {
            int temp = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j])
                    temp = max(length[j] + 1, temp);
            }
            length[i] = temp;
            m = max(m, length[i]);
        }
        return m;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章