673. Number of Longest Increasing Subsequence - Medium

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 longest continuous increasing subsequence is 1, and there are 5 subsequences' length is 1, so output 5.

 

Constraints:

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

 

dp, time = O(n ^ 2), space = O(n)

class Solution {
    public int findNumberOfLIS(int[] nums) {
        int n = nums.length;
        if(n <= 1) {
            return n;
        }
        int res = 0, maxLen = 0;
        int[] lengths = new int[n]; //lengths[i] = length of longest ending in nums[i]
        int[] counts = new int[n];  //count[i] = number of longest ending in nums[i]

        for(int i = 0; i < n; i++) {
            lengths[i] = counts[i] = 1;
            for(int j = 0; j < i; j++) {
                if(nums[j] < nums[i]) {
                    if(lengths[j] + 1 == lengths[i]) {
                        counts[i] += counts[j];
                    }
                    if(lengths[j] + 1 > lengths[i]) {
                        counts[i] = counts[j];
                        lengths[i] = lengths[j] + 1;
                    }
                }
            }
            if(lengths[i] == maxLen) {
                res += counts[i];
            }
            if(lengths[i] > maxLen) {
                maxLen = lengths[i];
                res = counts[i];
            }
        }
        return res;
    }
}

 

posted @ 2020-11-11 16:43  fatttcat  阅读(105)  评论(0编辑  收藏  举报