这是一道最长子序列题,子序列中的每一个数在原序列中不一定是相邻的,这一点要注意,用dp 解决,用dp[i]记录最后一个数字为nums[i]的最长子序列长度,用count[i]记录最后一个数字为nums[i]的最长子序列个数,
dp[i]=max(dp[j]+1),{j| j=0,1,2…i-1&&nums[j]<nums[i]},
count[i]=所有count[j]之和if(dp[j]+1==dp[i])
theAllMax代表dp中最大的那个值
最后dp[n]的值代表最长的子序列长度,for(eachint u in dp),当dp[u]== theAllMax的时候,sum+=count[u],最后sum的值就是最长子序列的个数
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
vector<int> dp(n);
vector<int> count(n, 0);
dp[0] = 1;
count[0] = 1;
int tmp,tmpCount;
int theAllMax = 1, theAllMaxCount=0;
for (int i = 1; i < n; i++)
{
tmp = 0; tmpCount = 0;
for (int j = i - 1; j >= 0; j--)
{
int t;
if (nums[i] > nums[j])
{
t = dp[j] + 1;
if (t > tmp) {
tmp = t;
tmpCount = count[j];
}
else if(t==tmp)
{
tmpCount += count[j];
}
}
}
if (tmp == 0) {
tmp = 1;
tmpCount = 1;
}
dp[i] = tmp;
count[i] = tmpCount;
if (tmp > theAllMax) {
theAllMax = tmp;
}
}
for (int i = 0; i < n; i++)
{
if (dp[i] == theAllMax)
theAllMaxCount += count[i];
}
return theAllMaxCount;
}
};