[LeetCode]Number of Longest Increasing Subsequence

题目描述:

LeetCode 673. 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.

题目大意:

给定未排序的整数,计算最长递增子序列的个数。

解题思路:

动态规划(Dynamic Programming)

数组dp[x]表示以x结尾的子序列中最长子序列的长度

数组dz[x]表示以x结尾的子序列中最长子序列的个数

状态转移方程见代码

Python代码:

class Solution(object):
    def findNumberOfLIS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxLIS= ans = 0
        size = len(nums)
        dp = [1] * size
        dz = [1] * size
        for x in range(size):
            for y in range(0, x):
                if nums[x] > nums[y]:
                    if dp[y] + 1 > dp[x]:
                        dp[x] = dp[y] + 1
                        dz[x] = dz[y]
                    elif dp[y] + 1 == dp[x]:
                        dz[x] += dz[y]
        maxLIS = max(dp + [0])
        ans = 0
        for p, z in zip(dp, dz):
            if p == maxLIS:
                ans += z
        return ans

 

本文链接:http://bookshadow.com/weblog/2017/09/10/leetcode-number-of-longest-increasing-subsequence/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论