673. Number of Longest Increasing Subsequence
Given an unsorted array of integers, find the number of longest increasing subsequence.
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.
Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
方法1: dynamic programming
Reference: 300. Longest Increasing Subsequence
思路:
非主流的dp,和300. Longest Increasing Subsequence相比,在一个dp来记录以nums[i]为结尾的longest increasing subseq的长度同时,用另一个vector<\int> cnt(n, 1)来记录,以dp[i]为长度的LIS有多少个,必须被同步更新。方法如下:dp, cnt 都被initialized to 1, 因为如果当前数位nums[i]大于之前的某一数位,该dp[j] + 1会被和dp[i]比较,如果更大,会被替换,并且此时不管cnt[i]是多少,都要被cnt[j]替换掉。但是如果dp[j] + 1 == dp[i],那么此时的cnt[i] += cnt[j],同一长度的不同LIS被累加,dp[i] 没有发生改变。result,mx作为全球变量在i的循环内被持续更新。
易错点:
- i 和 j的循环式,如何避免boundary:这里dp和nums是同样大小。
- 必须在i循环内更新全球变量,或者在循环式结束后再走两次遍历,找到LIS的计数。
Complexity
Time complexity: O(n^2)
Space complexity: O(n)
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
if (nums.empty()) return 0;
int n = nums.size();
vector<int> dp(n, 1);
vector<int> cnt(n, 1);
int mx = 0, result = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (dp[i] == dp[j] + 1) {
cnt[i] += cnt[j];
}
else if (dp[i] <= dp[j]) {
dp[i] = dp[j] + 1;
cnt[i] = cnt[j];
}
}
}
if (dp[i] == mx) {
result += cnt[i];
}
else if (dp[i] > mx) {
mx = dp[i];
result = cnt[i];
}
}
// int mx = 0, result = 0;
// for (int len: dp) {
// mx = max(len, mx);
// }
// for (int i = 0; i < n; i++) {
// if (dp[i] == mx) {
// result += cnt[i];
// }
// }
return result;
}
};