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.
思路:DP,先求最大的递增连续序列的个数,然后再DP到i位置位置形成j个连续子序列的个数
第二次DP要利用第一个DP数组求出来的信息
package l673;
class Solution {
public int findNumberOfLIS(int[] nums) {
if(nums.length == 0) return 0;
int max = 1;
int[] dp1 = new int[nums.length];
dp1[0] = 1;
for(int i=1; i nums[j])
dp1[i] = Math.max(dp1[i], 1+dp1[j]);
max = Math.max(max, dp1[i]);
}
int[][] dp = new int[nums.length][1+max];
for(int i=0; i nums[j])
dp[i][k+1] += dp[j][k];
}
}
}
int ret = 0;
for(int i=0; i
这个是O(N^3)的,用Python会TLE,其实后一过程可以优化为O(N^2),dp2[i]表示以i结尾,LIS长度为dp[i]的个数
class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums: return 0
n = len(nums)
Max_len = 0
# max_len[i]:max LIS length end with i, cnt[i]:count of current longest LIS length end with i
max_len, cnt = [0]*n, [0]*n
for i in range(n):
max_len[i] = 1
for j in range(i):
if nums[i]>nums[j]:
max_len[i] = max(max_len[i], max_len[j]+1)
Max_len = max(Max_len, max_len[i])
for i in range(n):
if max_len[i]==1:
cnt[i]=1
continue
for j in range(i):
if nums[i]>nums[j]:
if max_len[i] == max_len[j]+1:
cnt[i] += cnt[j]
return sum(cnt[i] for i in range(n) if max_len[i]==Max_len)
s=Solution()
print(s.findNumberOfLIS([2,2,2,2,2]))
print(s.findNumberOfLIS([1,3,5,4,7]))
print(s.findNumberOfLIS([1,3,2]))
然后2个循环可以写在一起
class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
n = len(nums)
cur_max = ret = 0
# max_len[i]:max LIS length end with i, cnt[i]:max count of current max LIS length
max_len, cnt = [0]*n, [0]*n
for i in range(n):
max_len[i] = cnt[i] = 1
for j in range(i):
if nums[i]>nums[j]:
if max_len[i]==max_len[j]+1: cnt[i]+=cnt[j]
elif max_len[i]