Skip to content

[LeetCode] 673. Number of Longest Increasing Subsequence #100

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
frdmu opened this issue Sep 20, 2021 · 0 comments
Open

[LeetCode] 673. Number of Longest Increasing Subsequence #100

frdmu opened this issue Sep 20, 2021 · 0 comments

Comments

@frdmu
Copy link
Owner

frdmu commented Sep 20, 2021

Given an integer array nums, return the number of longest increasing subsequences.

Notice that the sequence has to be strictly increasing.

 

Example 1:

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

Example 2:

Input: nums = [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.

 

Constraints:

  • 1 <= nums.length <= 2000
  • -106 <= nums[i] <= 106


解法:
类似300.求最长公共子序列的长度,这里又多了一步,求最长公共子序列的个数,所以需要再增加一个cnt[i],表示以元素nums[i]结尾的最长公共子序列的个数。代码如下:

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int n = nums.size();
        vector<int> dp(n, 1), cnt(n, 0);
        if (n <= 1) return n;
        cnt[0] = 1;
        
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i])
                    dp[i] = max(dp[i], dp[j]+1);   
            }
            for (int j = 0; j < i; j++) {
                if (dp[j]+1 == dp[i] && nums[j] < nums[i])
                    cnt[i] += cnt[j];
            }
            cnt[i] = max(cnt[i], 1); 
        }
              
        int max = -1, res = 0;
        for (int i = 0; i < n; i++) {
            if (dp[i] > max)
                max = dp[i];
        } 
        for (int i = 0; i < n; i++) {
            if (max == dp[i])
                res += cnt[i];
        }
        
        return res;
    } 
};
/*
 nums
 dp
 cnt

   1 2 4 3 5 4 7 2    
   1 2 3 3 4 4 5 2
   1 1 1 1 2 1 3 1 
   
   2 2 2 2 2 
   1 1 1 1 1
   1 1 1 1 1
   
   1 3 5 4 7
   1 2 3 3 4
   1 1 1 1 2
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant