673. Number of Longest Increasing Subsequence

粽子包子粿條發表於2020-12-16

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

來源:力扣(LeetCode)
連結:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence
著作權歸領釦網路所有。商業轉載請聯絡官方授權,非商業轉載請註明出處。

用兩個dp陣列,一個len[i]表示,到第i個數字,最長的子序列的長度。count[i]表示,第i個數字,最長的子序列的個數。

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if (nums.length <= 1) {
            return nums.length;
        }
        int []len = new int[nums.length];
        Arrays.fill(len, 1);
        int []count = new int[nums.length];
        Arrays.fill(count, 1);

        int max = 0;
        int maxCount = 0;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    if (len[i] == len[j] + 1) {
                        // 說明 nums[i] 這個數字可以加在以 nums[j] 結尾的遞增序列後面
                        // 則以 nums[j] 結尾的遞增序列個數可以直接加到以 nums[i] 結尾的遞增序列個數上
                        count[i] += count[j];
                    } else if (len[i] < len[j] + 1) {
                        // 說明找到了一條長度更長的遞增序列,直接更新len[i]和count[i],與j保持一致
                        len[i] = len[j] + 1;
                        count[i] = count[j];
                    }
                }
            }
            // 更新最終長度與最終答案
            if (len[i] == max) {
                maxCount += count[i];
            } else if (len[i] > max) {
                max = len[i];
                maxCount = count[i];
            }

        }
        return maxCount;
    }
}

 

 

相關文章