题目

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

Example 1:

  1. Input: nums = [1,3,5,4,7]
  2. Output: 2
  3. Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

  1. Input: nums = [2,2,2,2,2]
  2. Output: 5
  3. 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

  1. class Solution {
  2. public int findNumberOfLIS(int[] nums) {
  3. if (nums.length == 0) {
  4. return 0;
  5. }
  6. int[] len = new int[nums.length];
  7. int[] cnt = new int[nums.length];
  8. len[0] = 1;
  9. cnt[0] = 1;
  10. for (int i = 1; i < nums.length; i++) {
  11. int maxLen = 0, maxCnt = 1;
  12. for (int j = 0; j < i; j++) {
  13. if (nums[i] > nums[j]) {
  14. if (len[j] > maxLen) {
  15. maxLen = len[j];
  16. maxCnt = cnt[j];
  17. } else if (len[j] == maxLen) {
  18. maxCnt += cnt[j];
  19. }
  20. }
  21. }
  22. len[i] = maxLen + 1;
  23. cnt[i] = maxCnt;
  24. }
  25. int maxLen = 0, maxCnt = 0;
  26. for (int i = 0; i < nums.length; i++) {
  27. if (len[i] > maxLen) {
  28. maxLen = len[i];
  29. maxCnt = cnt[i];
  30. } else if (len[i] == maxLen) {
  31. maxCnt += cnt[i];
  32. }
  33. }
  34. return maxCnt;
  35. }
  36. }