给定一个未排序的整数数组,找到最长递增子序列的个数。
示例 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。
思路:动态规划问题,要将问题问题划分为若干状态,这道题定义状态 dp[i]表示以i位置结尾的,即nums[i]值结尾的最长连续递增的长度,dp初始化为1,因为最少自身可以作为一个递增子序列。当nums[i] > nums[j] (j < i)时,说明[...j,i]这段可以形成最长递增序列,长度是dp[j] + 1,反之,则不能形成最长递增序列。count[i] 表示以nums[i]结尾的最长递增子序列的组合数量。
class Solution {
public int findNumberOfLIS(int[] nums) {
if(nums == null || nums.length == 0) return 0;
int len = nums.length;
int[] dp = new int[len];
int[] count = new int[len];
int max = 0;
Arrays.fill(dp,1);
Arrays.fill(count,1);
// for(int i = 0; i < len; i++){
// count[i] = 1;
// }
// for(int i = 0; i < len; i++){
// dp[i] = 1;
// }
for(int i = 0; i < len; i++){
for(int j = 0; j < i; j++){
if(nums[j] < nums[i]){
//判断为true 说明第一次找到以nums[i]为结尾的最长递增子序列
if(dp[i] < dp[j] + 1){
dp[i] = dp[j] + 1;
// nums[j]结尾的最长递增子序列的组合数加上 i ,对组合数没有增加,只增加了子序列的长度
count[i] = count[j];
}else if(dp[j] + 1 == dp[i]){
//现在的组合方式 + count[j] 的组合方式
count[i] += count[j];
}
}
}
max = Math.max(max,dp[i]);
}
int res = 0;
for(int i = 0; i < len; i++){
if(dp[i] == max) res += count[i];
}
return res;
}
}