[LeetCode] 673. Number of Longest Increasing Subsequence

題目鏈接: https://leetcode.com/problems/number-of-longest-increasing-subsequence/description/

Description

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.

解題思路

動態規劃求解,建立兩個數組 lencnt
* len[k]: 表示以 nums[k] 爲末尾的最長子序列長度。
* cnt[k]: 表示以 nums[k] 爲末尾的最長子序列個數。

對於每一個 nums[i],只需要遍歷其前面的所有數字 nums[j] (0 <= j < i) ,找到比它小且長度最長的 nums[k],就可得出以 nums[i] 爲末尾的子序列的最大長度 len[i] = len[k] + 1 。同時,以 nums[i] 爲末尾的最長子序列個數應該等於 nums[j] (0 <= j < i) 中,比它小且長度最長的所有 nums[k] 的最長子序列個數之和。

用兩條公式來闡述上面一段難以理解的話
* len[k] = max(len[k], len[i] + 1), for all 0 <= i < k and nums[i] < nums[k]
* cnt[k] = sum(cnt[i]), for all 0 <= i < k and len[k] = len[i] + 1

舉個例子

nums = {1, 3, 5, 4, 7}

初始狀態,len = {1, 1, 1, 1, 1}cnt = {1, 1, 1, 1, 1}

開始遍歷,
* 數字 3,比它小的只有 1 => len[1] = len[0] + 1 = 2cnt[1] = cnt[0] = 1
* 數字 5,比它小且長度最長的爲 3 => len[2] = len[1] + 1 = 3cnt[2] = cnt[1] = 1
* 數字 4, 比它小且長度最長的爲 3 => len[3] = len[1] + 1 = 3cnt[3] = cnt[1] = 1
* 數字 7,比它小且長度最長的爲 5 和 4 => len[4] = len[2] + 1 = 4cnt[4] = cnt[2] + cnt[3] = 2

最終狀態,len = {1, 2, 3, 3, 4}cnt = {1, 1, 1, 1, 2}

Code

class Solution {
public:
    int findNumberOfLIS(vector<int>& nums) {
        int maxLen = 1;
        int res = 0;
        vector<int> len(nums.size(), 1);
        vector<int> cnt(nums.size(), 1);

        for (int i = 1; i < nums.size(); ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[j] < nums[i]) {
                    if (len[j] + 1 > len[i]) {
                        len[i] = len[j] + 1;
                        cnt[i] = cnt[j];
                    } else if (len[j] + 1 == len[i]) {
                        cnt[i] += cnt[j];
                    }
                }
            }
            maxLen = max(maxLen, len[i]);
        }


        for (int i = 0; i < nums.size(); ++i) {
            if (maxLen == len[i]) res += cnt[i];
        }

        return res;
    }
};
發佈了60 篇原創文章 · 獲贊 18 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章