How to Find the Length of the Longest Increasing Subsequence usi

  • 时间:2020-09-18 17:01:02
  • 分类:网络文摘
  • 阅读:138 次

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(n^2) complexity.
Follow up: Could you improve it to O(nlogn) time complexity?

Length of the Longest Increasing Subsequence using DP Algorithm

Surely, we can bruteforce, but that will take O(2^n) complexity i.e. each number has two choices: take or not take. This is not ideal. We could use f[i] to represent the longest length subsequence that ending at element nums[i]. Thus, we can reduce the runtime complexity to O(N^2) by checking each pair of (nums[j], nums[i]) and update f[i] = max(f[i], f[j] + 1) if nums[j] is smaller than nums[i].

The Longest Increasing Subsequence (LIS) can be computed via the following Dynamic Programming Algorithm i.e. C++.

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

Then, we need to find out the maximum value in f[0] to f.back(). The space requirement is O(N).

–EOF (The Ultimate Computing & Technology Blog) —

推荐阅读:
亡羊补牢为时已晚  数学题:用哪种方法得到的税后利息多一些  数学题:从甲袋中拿走17块巧克力,并在乙袋中放入7块巧克力  数学题:结果在距离A地占全程的五分之四处和乙车相遇  数学题:经几秒钟两人第二次相遇  数学题:妈妈买苹果和梨各用去多少钱?  求年利率的数学题  丝瓜菌菇鸡蛋汤营养美味之夏季消暑佳品  数学题:王老师平均每月要付给银行多少利息  数学题:一列火车通过250米长的道路用25秒 
评论列表
添加评论