文章目录
- 1 题目理解
- 2 动态规划
1 题目理解
Given an integer array nums, return the number of longest increasing subsequences.
Notice that the sequence has to be strictly increasing.
输入:整数数组int[] nums
输出:最长递增子序列的个数
规则:子序列是指从原数组中找出若干元素组成新的数组。这些元素不一定是下标相邻的,但是元素前后顺序不能变。递增子序列就是新的子数组中,i>j,a[i]>=a[j]。
2 动态规划
我们用dp[i]来记录以第i个元素为结尾的最长递增子序列的长度。
那么设j=0,1,2…i-1,当nums[i]>nums[j]的时候,dp[j]+1就是一个可能的值。从这些值中取最大值,就是dp[i]的值。
dp[i]=max(dp[j]+1),0<=j<i && nums[i]>nums[j]
同时我们用count[i]记录以nums[i]为结尾的最长递增子序列有多少个。
例如nums=[1,3,5,4,7];
处理第0个元素1:dp[0]=1,count[0]=1
处理第1个元素3:3>1,dp[1]=2,count[1]=count[0]=1
处理第2个元素5:5>1,dp[2]=2,count[2]=count[0]=1
5>3,dp[1]+1>dp[2],所以更新dp[2]=3,count[2]=count[1]=1
…
所以当遇到dp[j]+1>dp[i]的时候,count[i]=count[j],当遇到dp[j]+1==dp[i]的时候,count[i] +=count[j]。做叠加。
class Solution {public int findNumberOfLIS(int[] nums) {if(nums==null || nums.length == 0) return 0;int n = nums.length;int[] dp = new int[n];int[] count = new int[n];Arrays.fill(count,1);dp[0] = 1;int max = dp[0];for(int i=1;i<n;i++){dp[i] = 1;for(int j=i-1;j>=0;j--){if(nums[i]>nums[j]){if(dp[j]+1==dp[i]){count[i] +=count[j];}else if(dp[j]+1>dp[i]){count[i] = count[j];dp[i] = dp[j]+1;}}}max = Math.max(dp[i],max);}int c = 0;for(int i=0;i<n;i++){if(dp[i]==max){c +=count[i];}}return c;}
}