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

题目链接

英文链接:https://leetcode.com/problems/number-of-longest-increasing-subsequence/

中文链接:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence/

题目详述

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

示例 1:

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

示例 2:

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

注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。

题目详解

  • LeetCode300-最长上升子序列 是求最长上升子序列的长度,而本题是求最长上升子序列的个数。
  • 在原来的基础上多开一个数组,用来记录个数。
  • 最后返回长度最大值的个数。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
public class LeetCode_00673 {

public int findNumberOfLIS(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int n = nums.length;
int[] dp = new int[n];
int[] f = new int[n];
Arrays.fill(dp, 1);
Arrays.fill(f, 1);
int max = 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;
f[i] = f[j];
} else if (dp[j] + 1 == dp[i]) {
f[i] += f[j];
}
}
}
max = Math.max(max, dp[i]);
}
int res = 0;
for (int i = 0; i < n; ++i) {
if (dp[i] == max) {
res += f[i];
}
}
return res;
}
}