673. Number of Longest Increasing Subsequence

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
35
36
37
38
39
40
class Solution {
public int findNumberOfLIS(int[] nums) {
// 题目要求返回:最长递增子序列的个数

// 定义 f[i] 为以 nums[i] 结尾的最长递增子序列的长度
int[] f = new int[nums.length];

// 定义 g[i] 为以 nums[i] 结尾的最长递增子序列的个数
int[] g = new int[nums.length];

int maxLength = 1;
for (int i = 0; i < nums.length; i++) {
f[i] = g[i] = 1;

for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (f[j] + 1 > f[i]) {
// 出现了更长的子序列
f[i] = f[j] + 1;
g[i] = g[j];
} else if (f[j] + 1 == f[i]) {
// 可以组成长度相同的子序列,仅累加个数,不调整长度
g[i] += g[j];
}
}
}

maxLength = Math.max(maxLength, f[i]);
}

// [1, 1, 1, 1, 1] 的最长递增子序列的个数应该为 5 而不是 1
int count = 0;
for (int i = 0; i < f.length; i++) {
if (f[i] == maxLength) {
count += g[i];
}
}
return count;
}
}

References

673. Number of Longest Increasing Subsequence