题目
给定一个未排序的整数数组,找到最长递增子序列的个数。
示例
输入: [1,3,5,4,7]
输出: 2
解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
输入: [2,2,2,2,2]
输出: 5
解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。
注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法1:动态规划
定义两个函数:dp、count
Java实现
class Solution {
public int findNumberOfLIS(int[] nums) {
int n = nums.length;
//定义dp函数:dp[i]表示以nums[i]这个数结尾的最长递增子序列的 长度
int[] dp = new int[n];
//定义count函数:count[i]表示以nums[i]这个数结尾的最长递增子序列的 个数
int[] count = new int[n];
Arrays.fill(dp, 1);
Arrays.fill(count, 1);
int max = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1; //更新dp[i]
count[i] = count[j];
}
else if (dp[i] == dp[j] + 1) {
count[i] += count[j];
}
}
//找到最长的递增子序列长度
max = Math.max(max, dp[i]);
}
}
int ans = 0;
for (int i = 0; i < n; i++) {
if (dp[i] == max) ans += count[i];
}
return ans;
}
}