673. Number of Longest Increasing Subsequence
by Botao Xiao
Question
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.
Solution
- Method 1: dp
- dp[i]: up to current index, the max number of increasing subset.
- count[i]: the number of ways to keep the maximum dp number up to index i.
- update the maximum: we update the count to the previous ones, since we only need to append current value to all previous ones.
- if max is the same, we need to append current value to all previous ways.
class Solution { public int findNumberOfLIS(int[] nums) { int len = nums.length; if(len == 0) return 0; int[] dp = new int[len]; int[] count = new int[len]; Arrays.fill(dp, 1); Arrays.fill(count, 1); int max = 1; for(int i = 1; i < len; i++){ for(int j = i - 1; j >= 0; j--){ if(nums[i] > nums[j] && dp[j] + 1 > dp[i]){ dp[i] = dp[j] + 1; count[i] = count[j]; }else if(nums[i] > nums[j] && dp[j] + 1 == dp[i]){ count[i] += count[j]; } } max = Math.max(max, dp[i]); } int res = 0; for(int i = 0; i < len; i++){ if(dp[i] == max){ res += count[i]; } } return res; } }
Reference
Subscribe via RSS