• 0673. Number of Longest Increasing Subsequence (M)


    Number of Longest Increasing Subsequence (M)

    题目

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

    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:

    • 0 <= nums.length <= 2000
    • -10^6 <= nums[i] <= 10^6

    题意

    统计给定数组中最长递增子序列的个数。

    思路

    动态规划。建两个数组len和cnt:len[i]表示以第i个整数为结尾的递增子序列的长度,cnt[i]表示以第i个整数为结尾的递增子序列的个数。目标就是求len[i]最大时的cnt[i]的值。


    代码实现

    Java

    class Solution {
        public int findNumberOfLIS(int[] nums) {
            if (nums.length == 0) {
                return 0;
            }
    
            int[] len = new int[nums.length];
            int[] cnt = new int[nums.length];
            len[0] = 1;
            cnt[0] = 1;
    
            for (int i = 1; i < nums.length; i++) {
                int maxLen = 0, maxCnt = 1;
                for (int j = 0; j < i; j++) {
                    if (nums[i] > nums[j]) {
                        if (len[j] > maxLen) {
                            maxLen = len[j];
                            maxCnt = cnt[j];
                        } else if (len[j] == maxLen) {
                            maxCnt += cnt[j];
                        }
                    }
                }
                len[i] = maxLen + 1;
                cnt[i] = maxCnt;
            }
    
            int maxLen = 0, maxCnt = 0;
            for (int i = 0; i < nums.length; i++) {
                if (len[i] > maxLen) {
                    maxLen = len[i];
                    maxCnt = cnt[i];
                } else if (len[i] == maxLen) {
                    maxCnt += cnt[i];
                }
            }
    
            return maxCnt;
        }
    }
    
  • 相关阅读:
    Python常用转换函数
    Python随机数
    sublime text的pylinter插件设置pylint_rc后提示错误
    使用Pydoc生成文档
    字符编码笔记:ASCII,Unicode和UTF-8
    Windows编程MessageBox函数
    魔方阵算法及C语言实现
    iOS通讯录整合,兼容iOS789写法,附demo
    谈谈iOS app的线上性能监测
    ReactiveCocoa代码实践之-更多思考
  • 原文地址:https://www.cnblogs.com/mapoos/p/13904399.html
Copyright © 2020-2023  润新知