求最长LIS序列的的个数
sol:
刚开始写了个N^3的dp,dp[i][j]以i个数结尾LIS长度为k的个数,然后dp[i][j] += dp[k][j-1] num[k] < num[i],肯定是TLE 了.
其实我们有N^2的dp做法:
length[i] 表示第i个数结尾最大的LIS长度,cnt[i]表示以第i个数结尾的这个长度的个数
public int findNumberOfLIS(int[] nums) {
int len = nums.length;
//以第i个数结尾的最大长度
int[] length = new int[len];
//以第i个数结尾最大长度的对应序列个数
int[] cnt = new int[len];
for (int i = 0; i < len; i++) {
length[i] = 1;
cnt[i] =1;
}
int maxLength = 1;
for (int i = 1; i < len; i++) {
for (int j = 0; j < i; j++) {
if (nums[j] < nums[i]) {
if (length[j] + 1 == length[i]) {
cnt[i] += cnt[j];
} else if (length[j] + 1 > length[i]) {
length[i] = length[j] + 1;
cnt[i] = cnt[j];
}
}
}
maxLength = Math.max(maxLength, length[i]);
}
int res = 0;
for (int i = 0; i < len ;i++) {
if (length[i] == maxLength) res += cnt[i];
}
return res;
}
参考:https://blog.csdn.net/qq_37108878/article/details/85705088