#673 Number of Longest Increasing Subsequence

Description

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

Notice that the sequence has to be strictly increasing.

Examples

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
− 1 0 6 -10^6 106 <= nums[i] <= 1 0 6 10^6 106

思路

就是dp啦,可以参考300的方法1,多加入一个统计length的数组就可以了,不过感觉还能改进,因为现在的复杂度还是 O ( n 2 ) O(n^2) O(n2)

代码

class Solution {
    public int findNumberOfLIS(int[] nums) {
        int[] maxLength = new int[nums.length];
        int[] lengthCount = new int[nums.length];
        
        for(int i = 0; i < nums.length; i++){
            maxLength[i] = 1;
            lengthCount[i] = 0;
            for(int j = 0; j < i; j++){
                if (nums[i] > nums[j]){
                    maxLength[i] = Math.max(maxLength[i], maxLength[j] + 1);
                }
            }    
            for(int j = 0; j < i; j++){
                if (nums[i] > nums[j] && maxLength[i] == maxLength[j] + 1){
                   lengthCount[i] += lengthCount[j];
                }
            }
            lengthCount[i] = Math.max(1, lengthCount[i]);
        }
        
        int maxLen = 0;
        int lenCnt = 0;
        for (int i = 0; i < nums.length; i++){
            maxLen = Math.max(maxLen, maxLength[i]);
        }
        for (int i = 0; i < nums.length; i++){
            if (maxLength[i] == maxLen)
                lenCnt += lengthCount[i];
        }
        
        return lenCnt;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值