673. Number of Longest Increasing Subsequence

来源:互联网 发布:淘宝客服不理人 编辑:程序博客网 时间:2024/06/07 00:54

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.

Hint:
要找一个序列的最长递增子序列的数目,可以使用动态规划算法。

len[i]:前i项的最长子序列长度。
count[i]:记录前i项的最长子序列数目。
nums[i]:原输入串第i项

当i > j, nums[i] > nums[j]时, 意味着第i项可以与以第j项结尾的递增子序列结合成更长的递增子序列。
因此对每个i遍历它的前面所有项,找出所有满足nums[i] > nums[j]的j,计算出最长的一个递增子序列max{1+len[j]},即为len[i]的值。

len[i] = 1 + max{len[i], 1+len[j]} i > j, nums[i] > nums[j]

对count[i],当我们每次发现一个1+len[j]与当前len[i] (即当前所知最长子序列长度) 相等时,我们需要在count[i]基础上加上可以达到len[j]的所有可能count[j],即count[i] += count[j]。而当我们发现1+len[j]>len[i],意味着最长递增子序列的长度更新了,因此以前的count[i]不再是最长子序列的个数,要把count[i]重置。

最后找出max{len[i]},统计对应count,即为答案

时间复杂度O(n^2)

class Solution {public:    int findNumberOfLIS(vector<int>& nums) {        int size = nums.size();        vector<int> len(size,1);        vector<int> count(size,1);        int maxlen = 1;        for (int i = 0; i < size; i++) {            for (int j = 0; j < i; j++) {                if (nums[j] < nums[i]) {                    if (len[i] < 1+len[j]) {                        len[i] = 1+len[j];                        count[i] = count[j];                    } else if (len[i] == 1+len[j]) {                        count[i] += count[j];                    }                }            }            maxlen = max(maxlen,len[i]);        }        int result = 0;        for (int i = 0; i < size; i++) {            if (len[i] == maxlen) {                result += count[i];            }        }        return result;    }};
阅读全文
0 0
原创粉丝点击