LeetCode673. 最长递增子序列的个数

给定一个未排序的整数数组,找到最长递增子序列的个数。

示例 1:

输入: [1,3,5,4,7]
输出: 2
解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
示例 2:

输入: [2,2,2,2,2]
输出: 5
解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。

思路:动态规划问题,要将问题问题划分为若干状态,这道题定义状态 dp[i]表示以i位置结尾的,即nums[i]值结尾的最长连续递增的长度,dp初始化为1,因为最少自身可以作为一个递增子序列。当nums[i] > nums[j] (j < i)时,说明[...j,i]这段可以形成最长递增序列,长度是dp[j] + 1,反之,则不能形成最长递增序列。count[i] 表示以nums[i]结尾的最长递增子序列的组合数量。

图片来自https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/solution/dong-tai-gui-hua-jie-zui-chang-zi-xu-lie-zi-chua-4/

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int len = nums.length;
        int[] dp = new int[len];
        int[] count = new int[len];
        int max =  0;
        Arrays.fill(dp,1);
        Arrays.fill(count,1);
        // for(int i = 0; i < len; i++){
        //     count[i] = 1;
        // }
        // for(int i = 0; i < len; i++){
        //     dp[i] = 1;
        // }
        for(int i = 0; i < len; i++){
            for(int j = 0; j < i; j++){
                if(nums[j] < nums[i]){
                    //判断为true 说明第一次找到以nums[i]为结尾的最长递增子序列
                   if(dp[i] < dp[j] + 1){
                        dp[i] = dp[j] + 1;
                    // nums[j]结尾的最长递增子序列的组合数加上 i ,对组合数没有增加,只增加了子序列的长度
                        count[i] = count[j];
                    }else if(dp[j] + 1 == dp[i]){
                        //现在的组合方式 + count[j] 的组合方式
                        count[i] += count[j];
                    }   
                }    
                }
                max = Math.max(max,dp[i]);                 
            }
            int res = 0;
            for(int i = 0; i < len; i++){
                if(dp[i] == max) res += count[i];
            }
        return res;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值