原题链接:https://leetcode.com/problems/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: 2Example 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.
题目描述的大概意思就是给定一个无序数组nums,然后找出这个数组最长递增子序列的个数。题目刚开始做的时候,我就隐约感觉这是要用动态规划方程做的,但一直没分析出子问题和原问题之间的关系,即nums[i]和nums[i+1]的对应的最大子序列长度和其个数的关系。
后面开始用len[i]代表到nums[i]结束的最长子序列的长度,用cnt[i]代表最长子序列的个数,然后存在以下两个方程:
len[k+1] = max(len[k+1], len[i]+1) for all i <= k and nums[i] < nums[k+1];
cnt[k+1] = sum(cnt[i]) for all i <= k and nums[i] < nums[k+1] and len[i] = len[k+1]-1;
根据上述两个动态规划方程,即可进行编程,以下为源代码:
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
int n = nums.size(), maxlen = 1, ans = 0;
vector<int> cnt(n, 1), len(n, 1);
for (int i = 1; i < n; i++) {
for (int j = 0; j < i; j++) {
if (nums[i] > nums[j]) {
if (len[j]+1 > len[i]) {
len[i] = len[j]+1;
cnt[i] = cnt[j];
}
else if (len[j]+1 == len[i])
cnt[i] += cnt[j];
}
}
maxlen = max(maxlen, len[i]);
}
for (int i = 0; i < n; i++)
if (len[i] == maxlen) ans += cnt[i];
return ans;
}
};