首页 > 其他 > 详细

673. Number of Longest Increasing Subsequence - Medium

时间:2020-11-11 18:00:46      阅读:21      评论:0      收藏:0      [点我收藏+]

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;
    }
}

 

673. Number of Longest Increasing Subsequence - Medium

原文:https://www.cnblogs.com/fatttcat/p/13959449.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!