673. Number of Longest Increasing Subsequence

来源:互联网 发布:mysql入门经典pdf 编辑:程序博客网 时间:2024/06/07 02:59

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

Example 1:
Input: [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]
Output: 5
Explanation: The length of longest continuous increasing subsequence is 1, and there are 5 subsequences’ length is 1, so output 5.

两个并列的dynamic programming,一个记录截至到这一点,以这一点为结束点的,最大长度,一个记录到这一点的最大长度的递增序列有多少种。然后回过头在第一个长度的dynamic programming里找所有符合最大长度的节点,把到他们的各自的路径数目相加。

int findNumberOfLIS(vector<int>& nums) {    int len = nums.size();    if (len == 0) return 0;    vector<int> dp(len, 0);    vector<int> cnt(len, 1);    int maxlen = 0;    for (int i = 0; i < len; i++) {        int maxval = 0;        for (int j = 0; j < i; j++) {            if (nums[i] > nums[j]) {                maxval = max(maxval, dp[j]);            }        }        dp[i] = maxval + 1;        if (dp[i] > 1) {            int step = 0;            for (int j = 0; j < i; j++) {                if (nums[i] > nums[j] && dp[j] == maxval) step += cnt[j];            }            cnt[i] = step;        }        maxlen = max(maxlen, dp[i]);    }    int ans = 0;    for (int i = 0; i < len; i++) {        if (dp[i] == maxlen) ans += cnt[i];    }    return ans;}
阅读全文
0 0