Number of Longest Increasing Subsequence
Last updated
Last updated
// O(n^2) solution
class Solution {
public int findNumberOfLIS(int[] nums) {
if (nums == null || nums.length == 0) return 0;
int[] len = new int[nums.length];
int[] cnt = new int[nums.length];
len[0] = 1;
cnt[0] = 1;
for (int i = 1; i < nums.length; ++i) {
int max = 0, count = 1;
for (int j = 0; j < i; ++j) {
if (nums[j] < nums[i]) {
if (max < len[j]) {
count = cnt[j];
max = len[j];
} else if (max == len[j]) {
count += cnt[j];
}
}
}
len[i] = max + 1;
cnt[i] = count;
}
int max = 1, ret = 0;
for (int i = 0; i < nums.length; ++i) {
if (len[i] > max) {
max = len[i];
ret = cnt[i];
} else if (len[i] == max) {
ret += cnt[i];
}
}
return ret;
}
} class Solution(object):
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
LIS = [1] + [0] * (len(nums) - 1)
cnt = [1] + [0] * (len(nums) - 1)
for i in range(1, len(nums)):
maxLen, count = 0, 0
for j in range(i):
if nums[j] < nums[i]:
if maxLen < LIS[j]:
maxLen = LIS[j]
count = cnt[j]
elif maxLen == LIS[j]:
count += cnt[j]
if count == 0: count = 1
LIS[i] = maxLen + 1
cnt[i] = count
maxLen, ret = 1, 0
for i in range(len(nums)):
if LIS[i] > maxLen:
maxLen = LIS[i]
ret = cnt[i]
elif LIS[i] == maxLen:
ret += cnt[i]
return ret