原题链接在这里:https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/
题目:
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. longestLen[i]记录 到i的LIS长度. longestCount[i]记录到i的LIS个数.
Base Case 都是1.
更新, 对每个j<i, 若nums[i] > nums[j], 正常longestLen[j]+1应该是新的longestLen[i]的长度, 但若是已经相等说明之前已经有线能加到这个长度了,所以longestCount[i]就要加上longestCount[j].
result. 每个i维护最长LIS长度,若更新, 把longestCount[i]赋值给res. 若遇到相同的LIS长度,把longestCount[i]加到res中.
Time Complexity: O(n^2), n = nums.length.
Space: O(n).
AC Java:
1 class Solution { 2 public int findNumberOfLIS(int[] nums) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 int len = nums.length; 8 int [] longestLen = new int[len]; 9 int [] longestCount = new int[len]; 10 int res = 0; 11 int maxLen = 0; 12 for(int i = 0; i<nums.length; i++){ 13 longestLen[i] = 1; 14 longestCount[i] = 1; 15 for(int j = 0; j<i; j++){ 16 if(nums[j] < nums[i]){ 17 if(longestLen[j]+1 > longestLen[i]){ 18 longestLen[i] = longestLen[j]+1; 19 longestCount[i] = longestCount[j]; 20 }else if(longestLen[j]+1 == longestLen[i]){ 21 longestCount[i] += longestCount[j]; 22 } 23 } 24 } 25 26 if(longestLen[i] > maxLen){ 27 maxLen = longestLen[i]; 28 res = longestCount[i]; 29 }else if(longestLen[i] == maxLen){ 30 res += longestCount[i]; 31 } 32 } 33 return res; 34 } 35 }
是Longest Continuous Increasing Subsequence 的进阶题.
时间: 2024-10-22 03:46:31