您的位置:首页 > 产品设计 > UI/UE

LeetCode | 673. Number of Longest Increasing Subsequence中等偏难题 找寻数组里面最大长度的子串的个数

2018-01-18 17:58 531 查看
Givenan unsorted array of integers, find the number of longest increasingsubsequence.Example1:Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequenceare [1, 3, 4, 7] and [1, 3, 5, 7].
Example2:Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuousincreasing subsequence is 1, and there are 5 subsequences' length is 1, sooutput 5.
Note: Length of the given array will be not exceed 2000 and theanswer is guaranteed to be fit in 32-bit signed int.这是一道最长子序列题,子序列中的每一个数在原序列中不一定是相邻的,这一点要注意,用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
的值代表最长的子序列长度,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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  动态规划
相关文章推荐