300.Longest Increasing-Subsequence

题目描述

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?

我的解法

解题思路

用动态规划,状态转移方程应该为:
如果nums[i]>nums[j] (i>j)
dp[i] = max(dp[i], dp[j]+1)
最后的解就是dp数组中的最大值。

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.size() == 0return 0;
        vector<int> dp(nums.size(), 1);
        for (int i = 1; i < nums.size(); i++){
            for (int j = 0; j < i; j++){
                if (nums[i] > nums[j])
                    dp[i] = max(dp[j] + 1, dp[i]);
            }
        }
        return *max_element(dp.begin(), dp.end());
    }
};

Runtime: 76 ms, faster than 8.02% of C++ online submissions for Longest Increasing Subsequence.
Memory Usage: 6.5 MB, less than 100.00% of C++ online submissions for Longest Increasing Subsequence.