LeetCode 673. Number of Longest Increasing Subsequence 最长递增子序列的个数 (C++/Java)

题目:

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.

分析:

求出最长递增子序列的个数,我们使用lens[i]表示以nums[i]为结尾的递增子序列中元素的个数也就是长度,以time[i]表示以nums[i]为结尾的递增子序列出现的次数,遍历nums数组,维护这两个数组。

遍历nums[i]这个元素,都要和i前面的元素进行比较(用j进行遍历),如果nums[i]大于nums[j],意味着nums[i]可以拼接到nums[j]后面,产生一个更长的子序列,如果lens[i] < lens[j] +1,更新lens数组lens[i] = lens[j]+1,同时times[i] = times[j]。

如果lens[i]恰好等于lens[j] +1,意味着此时已经有和当前长度相同的子序列了,我们要更新times[i] += times[j],因为以nums[i]为结尾的子序列(长度为lens[i])已经出现过了,我们要加上出现的次数。

最后统计最大长度出现的次数,返回答案即可。

程序:

C++

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        auto lens = vector<int>(nums.size(), 1);
        auto times = vector<int>(nums.size(), 1);
        for(int i = 1; i < nums.size(); ++i){
            for(int j = 0; j < i; ++j){
                if(nums[j] >= nums[i])
                    continue;
                if(lens[j] + 1 > lens[i]){
                    lens[i] = lens[j] + 1;
                    times[i] = times[j];
                }
                else if(lens[j] + 1 == lens[i])
                    times[i] += times[j];
            }
        }
        int maxLen = 0;
        int res = 0;
        for(int i = 0; i < lens.size(); ++i){
            if(maxLen < lens[i]){
                maxLen = lens[i];
                res = times[i];
            }
            else if(lens[i] == maxLen)
                res += times[i];
        }
        return res;
    }
};

Java

class Solution {
    public int findNumberOfLIS(int[] nums) {
        if(nums.length == 0)
            return 0;
        int[] lens = new int[nums.length];
        int[] times = new int[nums.length];
        int maxLen = 1;
        for(int i = 0; i < nums.length; ++i){
            lens[i] = 1;
            times[i] = 1;
            for(int j = 0; j < i; ++j){
                if(nums[i] <= nums[j])
                    continue;
                if(lens[j] + 1 > lens[i]){
                    lens[i] = lens[j] + 1;
                    times[i] = times[j];
                }
                else if(lens[j] + 1 == lens[i]){
                    times[i] += times[j];
                }
            }
            maxLen = Math.max(maxLen, lens[i]);
        }
        int res = 0;
        for(int i = 0; i < lens.length; ++i){
            if(lens[i] == maxLen)
                res += times[i];
        }
        return res;
    }
}

猜你喜欢

转载自www.cnblogs.com/silentteller/p/12206983.html