1093 · Number of Longest Increasing Subsequence
Algorithms
Medium
Description
Example
Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences’ length is 1, so output 5.
解法1:DP。
注意:这个跟传统的LIS有点不一样,因为还要记录跟最大值相同的个数。
下面这几行代码很关键。如果dp[i]是刚发现的最大值,那么count[i]=count[j],否则如果是重复发现的,那么 count[i] += count[j];。
if (nums[j] < nums[i]) {
if (dp[i] < dp[j] + 1) {
dp[i] = dp[j] + 1;
count[i] = count[j];
} else if (dp[i] == dp[j] + 1) {
count[i] += count[j];
}
}
class Solution {
public:
/**
* @param nums: an array
* @return: the number of longest increasing subsequence
*/
int findNumberOfLIS(vector<int> &nums) {
int n = nums.size();
if (n <= 1) return n;
//dp[i]: the maximum continuously increasing length at ith position, and the maximum is nums[i]
vector<int> dp(n, 1);
//count[i]: the count of continuously increasing length at ith position
vector<int> count(n, 1);
int maxLen = 0, res = 0;
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;
count[i] = count[j];
} else if (dp[i] == dp[j] + 1) {
count[i] += count[j];
}
}
}
if (maxLen < dp[i]) {
maxLen = dp[i];
res = count[i];
} else if (maxLen == dp[i]) {
res += count[i];
}
}
return res;
}
};