673. Number of Longest Increasing Subsequence
来源:互联网 发布:淘宝客服不理人 编辑:程序博客网 时间:2024/06/07 00:54
Given an unsorted array of integers, find the number of longest increasing subsequence.
Example 1:
Input: [1,3,5,4,7]Output: 2Explanation: The two longest increasing subsequence are [1, 3, 4, 7] and [1, 3, 5, 7].
Example 2:
Input: [2,2,2,2,2]Output: 5Explanation: 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.
Hint:
要找一个序列的最长递增子序列的数目,可以使用动态规划算法。
len[i]:前i项的最长子序列长度。
count[i]:记录前i项的最长子序列数目。
nums[i]:原输入串第i项
当i > j, nums[i] > nums[j]时, 意味着第i项可以与以第j项结尾的递增子序列结合成更长的递增子序列。
因此对每个i遍历它的前面所有项,找出所有满足nums[i] > nums[j]的j,计算出最长的一个递增子序列max{1+len[j]},即为len[i]的值。
len[i] = 1 + max{len[i], 1+len[j]} i > j, nums[i] > nums[j]
对count[i],当我们每次发现一个1+len[j]与当前len[i] (即当前所知最长子序列长度) 相等时,我们需要在count[i]基础上加上可以达到len[j]的所有可能count[j],即count[i] += count[j]。而当我们发现1+len[j]>len[i],意味着最长递增子序列的长度更新了,因此以前的count[i]不再是最长子序列的个数,要把count[i]重置。
最后找出max{len[i]},统计对应count,即为答案
时间复杂度O(n^2)
class Solution {public: int findNumberOfLIS(vector<int>& nums) { int size = nums.size(); vector<int> len(size,1); vector<int> count(size,1); int maxlen = 1; for (int i = 0; i < size; i++) { for (int j = 0; j < i; j++) { if (nums[j] < nums[i]) { if (len[i] < 1+len[j]) { len[i] = 1+len[j]; count[i] = count[j]; } else if (len[i] == 1+len[j]) { count[i] += count[j]; } } } maxlen = max(maxlen,len[i]); } int result = 0; for (int i = 0; i < size; i++) { if (len[i] == maxlen) { result += count[i]; } } return result; }};
- 673. Number of Longest Increasing Subsequence
- leetcode 673. Number of Longest Increasing Subsequence
- [LeetCode] 673. Number of Longest Increasing Subsequence
- LeetCode 673.Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence
- Number of Longest Increasing Subsequence
- LWC 49:673. Number of Longest Increasing Subsequence
- (M)Dynamic Programming:673. Number of Longest Increasing Subsequence
- 673. Number of Longest Increasing Subsequence【Medium】 一维动归
- 【第十一周】673. Number of Longest Increasing Subsequence
- leetcode 673. Number of Longest Increasing Subsequence 动态规划DP
- Number of Longest Increasing Subsequence 解题报告
- LeetCode673. Number of Longest Increasing Subsequence
- Leetcode | Number of Longest Increasing Subsequence
- bzoj 2257 裴蜀定理
- sql语句大全
- 软件开发的噩梦--项目分支
- AngularJS
- C++逐行读取文件
- 673. Number of Longest Increasing Subsequence
- 【C/C++】计时函数比较
- 欢迎使用CSDN-markdown编辑器
- TensorFlow实现用于图像分类的卷积神经网络(代码详细注释)
- Pytorch从入门到精通(一):线性模型
- Java并发学习(三)-AbstractQueuedSynchronizer
- golang基础-etcd介绍与使用、etcd存取值、etcd监测数据写入
- 用栈实现队列的先进先出结构
- 文章标题