673. Number of Longest Increasing Subsequence

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

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值