LintCode 1093 · Number of Longest Increasing Subsequence (DP 好题)

1093 · Number of Longest Increasing Subsequence
Algorithms
Medium

Description
Example
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.

解法1:DP。
注意:这个跟传统的LIS有点不一样,因为还要记录跟最大值相同的个数。
下面这几行代码很关键。如果dp[i]是刚发现的最大值,那么count[i]=count[j],否则如果是重复发现的,那么 count[i] += count[j];。

                if (nums[j] < nums[i]) {
                    if (dp[i] < dp[j] + 1) {
                        dp[i] = dp[j] + 1;
                        count[i] = count[j];
                    } else if (dp[i] == dp[j] + 1) {
                        count[i] += count[j];
                    }
                }
class Solution {
public:
    /**
     * @param nums: an array
     * @return: the number of longest increasing subsequence
     */
    int findNumberOfLIS(vector<int> &nums) {
        int n = nums.size();
        if (n <= 1) return n;
        //dp[i]: the maximum continuously increasing length at ith position, and the maximum is nums[i]
        vector<int> dp(n, 1);
        //count[i]: the count of continuously increasing length at ith position
        vector<int> count(n, 1);
        int maxLen = 0, res = 0;

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[j] < nums[i]) {
                    if (dp[i] < dp[j] + 1) {
                        dp[i] = dp[j] + 1;
                        count[i] = count[j];
                    } else if (dp[i] == dp[j] + 1) {
                        count[i] += count[j];
                    }
                }
            }
            if (maxLen < dp[i]) {
                maxLen = dp[i];
                res = count[i];
            } else if (maxLen == dp[i]) {
                res += count[i];
            }
        }
        
        return res;
    }
};
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值