🔒 문제 (LeetCode 673)

Given an integer array nums, return the number of longest increasing subsequences.

Notice that the sequence has to be strictly increasing.

Constraints:

  • 1 <= nums.length <= 2000
  • -106 <= nums[i] <= 106

 

🌊 입출력

Example 1:

Input: nums = [1,3,5,4,7]
Output: 2
Explanation: The two longest increasing subsequences are [1, 3, 4, 7] and [1, 3, 5, 7].

Example 2:

Input: nums = [2,2,2,2,2]
Output: 5
Explanation: The length of the longest increasing subsequence is 1, and there are 5 increasing subsequences of length 1, so output 5.

 


 

🔑 해결

🌌 알고리즘 - DP

/**
 * @param {number[]} nums
 * @return {number}
 */
var findNumberOfLIS = function(nums) {
    const N = nums.length
    let answer = 0
    let max = 0 // 현재까지 찾은 longest increasing subsequnce 길이의 최대값
    let len = new Array(N).fill(1)  // nums[i]를 포함하는 longest increasing subsequnce 길이
    let cnt = new Array(N).fill(1)  // nums[i]를 포함하는 longest increasing subsequnces의 개수
    
    // nums의 요소들을 하나씩 포함해가면서 len, cnt 배열 업데이트
    for(let i = 0; i < N; i++) {
        for(let 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[i]) answer += cnt[i]
        if(max < len[i]) {
            max = len[i]
            answer = cnt[i]
        }
    }
    
    return answer
};

'코딩테스트 (JS) > DP' 카테고리의 다른 글

[JS] Delete Operation for Two Strings  (0) 2022.09.14
[JS] Longest Common Subsequence  (0) 2022.09.13
[JS] Word Break  (0) 2022.09.07
[JS] Decode Ways  (0) 2022.09.07
[JS] Arithmetic Slices  (0) 2022.09.06

+ Recent posts