Given an integer array nums
, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
Example 1:
Input: nums = [1,3,5,4,7] Output: 2 Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: nums = [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.
Constraints:
1 <= nums.length <= 2000
-106 <= nums[i] <= 106
similar problem: LIS
cnt
array records the number of longest sequence ending in nums[i]
class Solution:
def findNumberOfLIS(self, nums: List[int]) -> int:
maxLen, ans, n = 0, 0, len(nums)
dp, cnt = [1] * n, [1] * n
for i in range(n):
for j in range(i):
if nums[i] > nums[j]:
if dp[j] + 1 > dp[i]:
dp[i] = dp[j] + 1
cnt[i] = cnt[j]
elif dp[j] + 1 == dp[i]:
cnt[i] += cnt[j]
if dp[i] > maxLen:
maxLen = dp[i]
ans = cnt[i]
elif dp[i] == maxLen:
ans += cnt[i]
return ans
class Solution {
public int findNumberOfLIS(int[] nums) {
int maxLen = 0, ans = 0, n = nums.length;
int[] dp = new int[n];
int[] cnt = new int[n];
for (int i = 0; i < n; i++) {
dp[i] = 1;
cnt[i] = 1;
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
cnt[i] = cnt[j];
} else if (dp[j] + 1 == dp[i]) {
cnt[i] += cnt[j];
}
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
ans = cnt[i];
} else if (dp[i] == maxLen) {
ans += cnt[i];
}
}
return ans;
}
}
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int maxLen = 0, ans = 0, n = nums.size();
vector<int> dp(n, 1), cnt(n, 1);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < i; ++j) {
if (nums[i] > nums[j]) {
if (dp[j] + 1 > dp[i]) {
dp[i] = dp[j] + 1;
cnt[i] = cnt[j];
} else if (dp[j] + 1 == dp[i]) {
cnt[i] += cnt[j];
}
}
}
if (dp[i] > maxLen) {
maxLen = dp[i];
ans = cnt[i];
} else if (dp[i] == maxLen) {
ans += cnt[i];
}
}
return ans;
}
};
func findNumberOfLIS(nums []int) int {
maxLen, ans, n := 0, 0, len(nums)
dp, cnt := make([]int, n), make([]int, n)
for i := 0; i < n; i++ {
dp[i] = 1
cnt[i] = 1
for j := 0; j < i; j++ {
if nums[i] > nums[j] {
if dp[j]+1 > dp[i] {
dp[i] = dp[j] + 1
cnt[i] = cnt[j]
} else if dp[j]+1 == dp[i] {
cnt[i] += cnt[j]
}
}
}
if dp[i] > maxLen {
maxLen = dp[i]
ans = cnt[i]
} else if dp[i] == maxLen {
ans += cnt[i]
}
}
return ans
}
impl Solution {
pub fn find_number_of_lis(nums: Vec<i32>) -> i32 {
let mut max_len = 0;
let mut ans = 0;
let n = nums.len();
let mut dp = vec![1; n];
let mut cnt = vec![1; n];
for i in 0..n {
for j in 0..i {
if nums[i] > nums[j] {
if dp[j] + 1 > dp[i] {
dp[i] = dp[j] + 1;
cnt[i] = cnt[j];
} else if dp[j] + 1 == dp[i] {
cnt[i] += cnt[j];
}
}
}
if dp[i] > max_len {
max_len = dp[i];
ans = cnt[i];
} else if dp[i] == max_len {
ans += cnt[i];
}
}
ans
}
}