673. Number of Longest Increasing Subsequence

Number of Longest Increasing Subsequence

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.

這題挺難的,看到LIS自然想到DP,但這題是二維DP,除了常規(guī)的len[]來記錄end with當(dāng)前數(shù)字的LIS長度,還需要一個維度cnt[]記錄end with當(dāng)前數(shù)字(必須包含當(dāng)前數(shù)字,比如1,2,4,3, cnt[3]是1而不是2)的LIS個數(shù)。

注意,這些DP都是強(qiáng)調(diào)一個end with,也就是「必須包含當(dāng)前數(shù)字」。
因?yàn)楸容^的過程中都是拿當(dāng)前數(shù)字跟前面的數(shù)字比,且若當(dāng)前數(shù)字不比前面的數(shù)字大,len[i]將一直維持在1。

最后,LIS的轉(zhuǎn)移方程不要記反了(我一開始記成len[i] + 1了,是錯的): if (len[i] < len[j] + 1) {len[i] = len[j] + 1;}

    public int findNumberOfLIS(int[] nums) {
        int n = nums.length, res = 0, max_len = 0;
        int[] len = new int[n], cnt = new int[n];
        for (int i = 0; i < n; i++) {
            len[i] = cnt[i] = 1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    if (len[i] == len[j] + 1)
                        cnt[i] += cnt[j];
                    if (len[i] < len[j] + 1) {
                        len[i] = len[j] + 1;
                        cnt[i] = cnt[j];
                    }
                }
            }
            if (max_len < len[i]) {
                max_len = len[i];
            }
        }
                //所有的長度等于max_len的cnt,加起來
        for (int i = 0; i < nums.length; i++) {
            if (len[i] == max_len) {
                res += cnt[i];
            }
        }
        return res;
    }

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容