(M)Dynamic Programming:673. Number of Longest Increasing Subsequence

本文介绍了一种使用动态规划解决最长递增子序列问题的方法,并提供了详细的代码实现。通过两个DP数组分别记录最长递增子序列的长度及其数量,最终找出所有最长递增子序列的数量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


这个题并不难,但是我一开始递归关系找错了。这个题考虑建立两个dp数组,一个存最长递增数组的长度,另一个存这个长度有多少条。下面是参考讨论区解法之后我的AC的代码:

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int n = nums.size();
        if(n == 0)
            return 0;
        vector<int> longest(n, 1);
        vector<int> count(n, 1);
        int length = 1;
        int res = 0;
        for(int i = 1; i < n; ++i)
        {
            for(int j = i - 1; j >= 0; --j)
            {
                if(nums[i] > nums[j])
                {
                    if(longest[i] < longest[j] + 1)
                    {
                        longest[i] = longest[j] + 1;
                        count[i] = count[j];                  //不是count[i] +=  1;!
                    }
                    else if(longest[i] == longest[j] + 1)
                    {
                        count[i] += count[j];               // 不是count[i] = count[j];!
                    }
                }
                
            }
            length = max(length, longest[i]);
        }
        for (int i = 0; i < n; i++) 
            if (longest[i] == length) res += count[i];
        return res;
    }
};

下面是讨论区代码:

int findNumberOfLIS(vector<int>& nums) {
        int n = nums.size(), res = 0, max_len = 0;
        vector<pair<int,int>> dp(n,{1,1});            //dp[i]: {length, number of LIS which ends with nums[i]}
        for(int i = 0; i<n; i++){
            for(int j = 0; j <i ; j++){
                if(nums[i] > nums[j]){
                    if(dp[i].first == dp[j].first + 1)dp[i].second += dp[j].second;
                    if(dp[i].first < dp[j].first + 1)dp[i] = {dp[j].first + 1, dp[j].second};
                }
            }
            if(max_len == dp[i].first)res += dp[i].second;
            if(max_len < dp[i].first){
                max_len = dp[i].first;
                res = dp[i].second;
            }
        }
        return res;
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值