Q:给定一个未排序的整数数组,找到最长递增子序列的个数。
示例 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位有符号整数。
A: 找最长递增子序列长度:(这个比较简单,就找了一个现成的)
public int lengthOfLIS(int[] nums) {
int[] dp = new int[nums.length];
// dp 数组全都初始化为 1
Arrays.fill(dp, 1);
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j])
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
int res = 0;
for (int i = 0; i < dp.length; i++) {
res = Math.max(res, dp[i]);
}
return res;
}
找个数时,放一个count数组。
public int findNumberOfLIS(int[] nums) {
if (nums.length <= 1)
return nums.length;
int n = nums.length;
int[] length = new int[n];
int[] count = new int[n];
Arrays.fill(length, 1);
Arrays.fill(count, 1);
int maxLen = 0;
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (length[i] < length[j] + 1) {//更新最大长度子序列
length[i] = length[j] + 1;
count[i] = count[j];
} else if (length[i] == length[j] + 1) {//同样以i结尾的最大长度的子序列
count[i] += count[j];
}
}
}
maxLen = Math.max(maxLen, length[i]);
}
int res = 0;
for (int i = 0; i < n; i++) {
if (maxLen == length[i])
res += count[i];
}
return res;
}