leetcode 673. Number of Longest Increasing Subsequence

来源:互联网 发布:大学生网络诈骗统计图 编辑:程序博客网 时间:2024/06/05 09:57

写在前面

contest 49最后一题。一道简单的动态规划题目,可是在做的时候总是想用贪婪算法解决,事实上是不可解的,另外,在求得最长连续序列后,我的想法是回溯求所有可能,最后导致超时,其实只需要在原先方法基础上修改即可,仍然是dp问题。

题目描述

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.

思路分析

之所以第一时间想到的是贪婪算法,可能还是对题目的理解不够全面,认为第一个开始递增的数一定是序列开始(稍微一个极端的例子就可以说明这个思路是错的,比如序列 [1,2,-100,-99,….0] 按照贪婪的思路得到的长度是2,而事实上最长子序列是从-100到0),当然如果接触过LIS,会知道它的标准解法就是经典的动态规划,令dp[i]表示以nums[i]结尾的最长子序列,最后对dp的结果求max即可,我们先写出求最长递增序列的代码。

1.最长递增子序列

class Solution {public:    int LengthOfLIS(vector<int>& nums) {        // 就是一个dp        vector<int> dp(nums.size(),1);        int maxLen = 1;        for(int i = 1;i<nums.size();++i) {            for(int j = 0;j<i;++j) {                if(nums[i]>nums[j]) {                    if(dp[i]<dp[j]+1){                        dp[i] = dp[j]+1;                    }                }            }            maxLen = max(maxLen,dp[i]);        }        return maxLen;    }};

2.最长递增子序列的个数

我们知道上述解法,核心就是不断更新dp[i],从而得到当前的最优解。然而,最优解可能不止一个,这种情况会发生在 dp[i] == dp[j]+1,即i与j具有相同的序列长度,那么我们更新当前长度ct[i] = ct[i]+ct[j]若dp[j]+1>dp[i],则更新最长子序列的个数为dp[j]的个数,最终写出的代码如下:

class Solution {public:    int findNumberOfLIS(vector<int>& nums) {        // 就是一个dp        vector<int> dp(nums.size(),1);        vector<int> ct(nums.size(),1);        int maxLen = 1;        for(int i = 1;i<nums.size();++i) {            for(int j = 0;j<i;++j) {                if(nums[i]>nums[j]) {                    if(dp[i]<dp[j]+1){                        dp[i] = dp[j]+1;                        ct[i] = ct[j];                    }                    else if(dp[i] == dp[j]+1){                        ct[i]+=ct[j];                    }                }            }            maxLen = max(maxLen,dp[i]);        }        int ret = 0;        for(int i = 0;i<ct.size();++i) if(dp[i]==maxLen) ret+=ct[i];        return ret;    }};
阅读全文
0 0
原创粉丝点击