Skip to content

Latest commit

 

History

History

673

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 

Given an integer array nums, return the number of longest increasing subsequences.

Notice that the sequence has to be strictly increasing.

 

Example 1:

Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.

 

Constraints:

  • 1 <= nums.length <= 2000
  • -106 <= nums[i] <= 106

Companies: Amazon, Google, Bloomberg

Related Topics:
Array, Dynamic Programming, Binary Indexed Tree, Segment Tree

Similar Questions:

Solution 1. DP

Consider the subproblem in range A[0..i] and the LIS must ends with A[i].

Let len[i] be the length of longest LIS ending with A[i].

Let cnt[i] be the count of longest LIS ending with A[i].

len[i] = 1 + max( len[j] | 0 <= j < i && A[j] < A[i] )
cnt[i] = sum( cnt[j] | 0 <= j < i && len[j] + 1 == len[i] )

The answer is

sum( cnt[i] | len[i] == maxLen )
    where maxLen = max( len[i] | 0 <= i < N )
// OJ: https://leetcode.com/problems/number-of-longest-increasing-subsequence/
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
public:
    int findNumberOfLIS(vector<int>& A) {
        if (A.empty()) return 0;
        int N = A.size(), ans = 0, maxLen = 0;
        vector<int> len(N, 1), cnt(N, 1);
        for (int i = 0; i < N; ++i) {
            for (int j = 0; j < i; ++j) {
                if (A[j] >= A[i]) continue;
                if (len[i] < 1 + len[j]) len[i] = 1 + len[j], cnt[i] = cnt[j];
                else if (len[i] == 1 + len[j]) cnt[i] += cnt[j];
            }
            if (len[i] > maxLen) maxLen = len[i], ans = cnt[i];
            else if (len[i] == maxLen) ans += cnt[i];
        }
        return ans;
    }
};

Solution 2. Top-down DP

// OJ: https://leetcode.com/problems/number-of-longest-increasing-subsequence
// Author: github.com/lzl124631x
// Time: O(N^2)
// Space: O(N)
class Solution {
public:
    int findNumberOfLIS(vector<int>& A) {
        int N = A.size(), maxLen = 0, ans = 0;
        vector<int> len(N), cnt(N);
        function<void(int)> dp = [&](int i) {
            if (i == N || len[i]) return;
            len[i] = 1;
            cnt[i] = 1;
            for (int j = 0; j < i; ++j) {
                if (A[j] >= A[i]) continue;
                dp(j);
                if (len[i] < 1 + len[j]) len[i] = 1 + len[j], cnt[i] = cnt[j];
                else if (len[i] == 1 + len[j]) cnt[i] += cnt[j];
            }
        };
        for (int i = 0; i < N; ++i) {
            dp(i);
            if (len[i] > maxLen) maxLen = len[i], ans = cnt[i];
            else if (len[i] == maxLen) ans += cnt[i];
        }
        return ans;
    }
};