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

来源:互联网 发布:b2b源码授权费用 编辑:程序博客网 时间:2024/06/05 17:34


这个题并不难,但是我一开始递归关系找错了。这个题考虑建立两个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;    }





阅读全文
0 0
原创粉丝点击