673. Number of Longest Increasing Subsequence

Number of Longest Increasing Subsequence

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.

这题挺难的,看到LIS自然想到DP,但这题是二维DP,除了常规的len[]来记录end with当前数字的LIS长度,还需要一个维度cnt[]记录end with当前数字(必须包含当前数字,比如1,2,4,3, cnt[3]是1而不是2)的LIS个数。

注意,这些DP都是强调一个end with,也就是「必须包含当前数字」。
因为比较的过程中都是拿当前数字跟前面的数字比,且若当前数字不比前面的数字大,len[i]将一直维持在1。

最后,LIS的转移方程不要记反了(我一开始记成len[i] + 1了,是错的): if (len[i] < len[j] + 1) {len[i] = len[j] + 1;}

    public int findNumberOfLIS(int[] nums) {
        int n = nums.length, res = 0, max_len = 0;
        int[] len = new int[n], cnt = new int[n];
        for (int i = 0; i < n; i++) {
            len[i] = cnt[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    if (len[i] == len[j] + 1)
                        cnt[i] += cnt[j];
                    if (len[i] < len[j] + 1) {
                        len[i] = len[j] + 1;
                        cnt[i] = cnt[j];
                    }
                }
            }
            if (max_len < len[i]) {
                max_len = len[i];
            }
        }
                //所有的长度等于max_len的cnt,加起来
        for (int i = 0; i < nums.length; i++) {
            if (len[i] == max_len) {
                res += cnt[i];
            }
        }
        return res;
    }

你可能感兴趣的:(673. Number of Longest Increasing Subsequence)