673. Number of Longest Increasing Subsequence

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

Rust Solution

struct Solution;

impl Solution {
    fn find_number_of_lis(nums: Vec<i32>) -> i32 {
        let n = nums.len();
        let mut len: Vec<usize> = vec![1; n];
        let mut cnt: Vec<usize> = vec![1; n];
        for i in 0..n {
            for j in 0..i {
                if nums[j] < nums[i] {
                    if len[j] + 1 == len[i] {
                        cnt[i] += cnt[j];
                    }
                    if len[j] == len[i] {
                        len[i] += 1;
                        cnt[i] = cnt[j];
                    }
                }
            }
        }
        let max_len = *len.iter().max().unwrap();
        let mut res = 0;
        for i in 0..n {
            if len[i] == max_len {
                res += cnt[i];
            }
        }
        res as i32
    }
}

#[test]
fn test() {
    let nums = vec![1, 3, 5, 4, 7];
    let res = 2;
    assert_eq!(Solution::find_number_of_lis(nums), res);
    let nums = vec![2, 2, 2, 2, 2];
    let res = 5;
    assert_eq!(Solution::find_number_of_lis(nums), res);
}

Having problems with this solution? Click here to submit an issue on github.