673. Number of Longest Increasing Subsequence

来源:互联网 发布:淘宝直通车推广费钱吗 编辑:程序博客网 时间:2024/06/14 20:53

Given an unsorted array of integers, find the number of longest increasing subsequence.

Example 1:

Input: [1,3,5,4,7]Output: 2Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: [2,2,2,2,2]Output: 5Explanation: 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.


分析

设lengths[i]为以nums[i]结尾的最长子序列的长度,counts[i]为以nums[i]为以nums[i]结尾的最长子序列的数量。

对于某个j,对于每个i,i满足i<j且nums[i]<nums[j]:

如果lengths[i] >= length[j],说明我们发现了更长的子序列,以nums[j]结尾,将length[j]更新为length[i]+1,count[j]=count[i];

如果lengths[i]+1=length[j],说明还有counts[i]个以nums[j]结尾的子序列,所以counts[j]+=counts[i];

如果lengths[i]+1<length[j],则无需更新,什么也不做。

找出最大的lengths[i]为longest;

计数longest的数目。


class Solution {public:    int findNumberOfLIS(vector<int>& nums) {int N = nums.size();        if (N <= 1) return N;        int lengths[N]; //lengths[i] = length of longest ending in nums[i]        int counts[N]; //count[i] = number of longest ending in nums[i]        for (int i = 0; i < N; ++i) {        counts[i]=1;        lengths[i]=1;        }         for (int j = 0; j < N; ++j) {            for (int i = 0; i < j; ++i) if (nums[i] < nums[j]) {                if (lengths[i] >= lengths[j]) {                    lengths[j] = lengths[i] + 1;                    counts[j] = counts[i];                } else if (lengths[i] + 1 == lengths[j]) {                    counts[j] += counts[i];                }            }        }        int longest = 0, ans = 0;        for (int i = 0; i < N; ++i) {            longest = max(longest, lengths[i]);        }        for (int i = 0; i < N; ++i) {            if (lengths[i] == longest) {                ans += counts[i];            }        }        return ans;          }};


阅读全文
0 0
原创粉丝点击