leetcode 673. 最长递增子序列的个数

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

示例 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。
注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。

方法:dp[n]为以nums[n]结尾最长递增子序列的长度,counter[n]表示nums[n]结尾的最长递增子序列的个数,因为dp数组是逐渐产生的,在后面的数大于前面的条件下由前面的dp加一产生,因为初始化dp都是1第一次更新会修改,那么dp由前面再次得到同样的值,说明存在其他的最长递增子序列,由此更新counter的值。

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if(nums == null || nums.length == 0) return 0;
        int n = nums.length;
        int[] dp = new int[n];
        int[] counter = new int[n];
        Arrays.fill(dp, 1);
        Arrays.fill(counter, 1);

        int res = 0;
        for(int i = 0; i < n; i++){
            for(int j = 0; j < i; j++){
                if(nums[i] > nums[j]){
                    if(dp[j] + 1 > dp[i]){
                        dp[i] = dp[j] + 1;
                        counter[i] = counter[j];
                    }
                    else if(dp[j] + 1 == dp[i]){
                        counter[i] += counter[j];
                    }
                }
            }
            res = Math.max(res, dp[i]);
        }
        int ans = 0;
        for(int i = 0; i < n; i++){
            if(dp[i] == res)
                ans += counter[i];
        }
        return ans;
    }
}

你可能感兴趣的:(leetcode,动态规划)