#include <vector>
#include <iostream>
using namespace std;
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
pair<int, int> result(1, 0); //长度 + 数量
vector<pair<int, int>> count(nums.size(), pair<int, int>(1, 1)); //每个位置的最长递增子序列长度 + 数量
for (int i = 0; i < nums.size(); ++i)
{
for (int j = 0; j < i; ++j) {
//左边的数字 小于 当前位置的数字 && 左边数字的位置的LIS + 1 >= 当前位置的LIS
if (nums[j] < nums[i] && count[j].first + 1 >= count[i].first) {
//如果LIS相同,则将相同LIS的数量进行累加
if (count[i].first == count[j].first + 1) {
count[i].second += count[j].second;
}
//LIS不相同,则更新大的LIS并且更新LIS的数量
else {
count[i].first = count[j].first + 1;
count[i].second = count[j].second;
}
}
}
//不断记录LIS 以及 重复的个数
//更新LIS和数量
if (result.first < count[i].first) {
result.first = count[i].first;
result.second = count[i].second;
}
//最大的LIS相同,则累加数量
else if (result.first == count[i].first)
result.second += count[i].second;
}
return result.second;
}
};
LeetCode. 673. 最长递增子序列的个数(动态规划 + 状态累计)
最新推荐文章于 2023-09-16 20:18:07 发布