LeetCode--673--medium--NumberOfLongestIncreasingSubsequences

package com.app.main.LeetCode.dynamic;

/**
 * 673
 *
 * medium
 *
 * https://leetcode.com/problems/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.
 * Note: Length of the given array will be not exceed 2000 and the answer is guaranteed to be fit in 32-bit signed int.
 *
 *
 *
 [3,1,2]
 [1,3,5,4,7]
 [1,2,4,3,5,4,7,2]
 * Created with IDEA
 * author:Dingsheng Huang
 * Date:2020/1/2
 * Time:下午3:10
 */
public class NumberOfLongestIncreasingSubsequences {

    public int findNumberOfLIS(int[] nums) {
        if (nums.length == 0) {
            return 0;
        }
        int max = 1;
        int cn = 1;

        int[] dp = new int[nums.length];
        int[] dpHelp = new int[nums.length];
        dpHelp[0] = 1;
        dp[0] = 1;

        for (int i = 1; i < nums.length; i++) {
            dp[i] = 1;
            int tmpcn = 0;
            for (int j = i - 1; j >= 0; j--) {
                if (nums[i] > nums[j]) {
                    if (dp[j] + 1 == dp[i]) {
                        tmpcn += dpHelp[j];
                    } else if (dp[j] + 1 > dp[i]){
                        tmpcn = dpHelp[j];
                        dp[i] = dp[j] + 1;
                    }
                }
            }
            dpHelp[i] = tmpcn == 0 ? 1 : tmpcn;
            if (dp[i] == max) {
                cn += tmpcn;
            } else if (dp[i] > max) {
                cn = tmpcn;
                max = dp[i];
            }
        }
        // handle corner case
        if (max == 1) {
            return nums.length;
        }
        return cn;
    }
}
发布了187 篇原创文章 · 获赞 26 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/huangdingsheng/article/details/103809804