-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
0673-number-of-longest-increasing-subsequence.kt
86 lines (74 loc) · 2.19 KB
/
0673-number-of-longest-increasing-subsequence.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/*
* DFS + memoization solution
*/
class Solution {
fun findNumberOfLIS(nums: IntArray): Int {
val memo = HashMap<Int, Pair<Int, Int>>()
var lisLen = 0
var lisCount = 0
fun dfs(i: Int): Pair<Int, Int> {
if (i in memo)
return memo[i]!!
var maxLen = 1
var maxCount = 1
for (j in i+1 until nums.size) {
if (nums[i] < nums[j]) {
val (curLen, curCount) = dfs(j)
if (curLen + 1 > maxLen) {
maxLen = curLen + 1
maxCount = curCount
} else if (curLen + 1 == maxLen) {
maxCount += curCount
}
}
}
if (maxLen > lisLen) {
lisLen = maxLen
lisCount = maxCount
} else if (maxLen == lisLen) {
lisCount += maxCount
}
memo[i] = (maxLen to maxCount)
return memo[i]!!
}
for (i in nums.indices)
dfs(i)
return lisCount
}
}
/*
* DP solution
*/
class Solution {
fun findNumberOfLIS(nums: IntArray): Int {
val lis = IntArray(nums.size) {1}
val count = IntArray(nums.size)
var lisLen = 0
var lisCount = 0
for (i in nums.size-1 downTo 0) {
var maxLen = 1
var maxCount = 1
for (j in i+1 until nums.size) {
if (nums[i] < nums[j]) {
val curLen = lis[j]
val curCount = count[j]
if (curLen + 1 > maxLen) {
maxLen = curLen + 1
maxCount = curCount
} else if (curLen + 1 == maxLen) {
maxCount += curCount
}
}
}
if (maxLen > lisLen) {
lisLen = maxLen
lisCount = maxCount
} else if (maxLen == lisLen) {
lisCount += maxCount
}
lis[i] = maxLen
count[i] = maxCount
}
return lisCount
}
}