增加673. 最长递增子序列的个数 JavaScript版本

This commit is contained in:
jerryfishcode
2021-09-27 20:48:55 +08:00
committed by GitHub
parent 8edca00e48
commit 5a10b329da

View File

@ -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;
};
```
-----------------------