mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-07 15:45:40 +08:00
增加673. 最长递增子序列的个数 JavaScript版本
This commit is contained in:
@ -337,6 +337,28 @@ func findNumberOfLIS(nums []int) int {
|
||||
## JavaScript
|
||||
|
||||
```js
|
||||
var findNumberOfLIS = function(nums) {
|
||||
const len = nums.length;
|
||||
if(len <= 1) return len;
|
||||
let dp = new Array(len).fill(1); // i之前(包括i)最长递增子序列的长度为dp[i]
|
||||
let count = new Array(len).fill(1); // 以nums[i]为结尾的字符串,最长递增子序列的个数为count[i]
|
||||
let res = 0;
|
||||
for(let i = 1; i < len; i++){
|
||||
for(let j = 0; j < i; j++){
|
||||
if(nums[i] > nums[j]){
|
||||
if(dp[j] + 1 > dp[i]){ // 第 j 个数字为前一个数字的子序列是否更更长
|
||||
dp[i] = dp[j] + 1; //更新 dp[i]
|
||||
count[i] = count[j]; // 重置count[i]
|
||||
} else if(dp[j] + 1 === dp[i]){ // 和原来一样长
|
||||
count[i] += count[j]; //更新count[i]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let max = Math.max(...dp); //扩展运算符找到最大长度
|
||||
for(let i = 0; i < len; i++) if(dp[i] === max) res += count[i]; // 累加
|
||||
return res;
|
||||
};
|
||||
```
|
||||
|
||||
-----------------------
|
||||
|
Reference in New Issue
Block a user