Skip to content

Commit 2a2fb2f

Browse files
authored
Create 0368-largest-divisible-subset.kt
1 parent 77af493 commit 2a2fb2f

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// DP top-down tabulation
2+
class Solution {
3+
fun largestDivisibleSubset(nums: IntArray): List<Int> {
4+
val n = nums.size
5+
nums.sort()
6+
val dp = nums
7+
.map { listOf(it) }
8+
.toTypedArray()
9+
var res = listOf<Int>()
10+
11+
for (i in n - 1 downTo 0) {
12+
for (j in i + 1 until n) {
13+
if (nums[j] % nums[i] == 0) {
14+
val temp = listOf(nums[i]) + dp[j]
15+
dp[i] = if (temp.size > dp[i].size) temp else dp[i]
16+
}
17+
}
18+
19+
res = if (dp[i].size > res.size) dp[i] else res
20+
}
21+
22+
return res
23+
}
24+
}
25+
26+
// recursion + memoization
27+
class Solution {
28+
fun largestDivisibleSubset(nums: IntArray): List<Int> {
29+
val n = nums.size
30+
nums.sort()
31+
val dp = HashMap<Int, List<Int>>()
32+
33+
fun dfs(i: Int): List<Int> {
34+
if (i == n) return listOf()
35+
dp[i]?.let { return it }
36+
37+
var res = listOf(nums[i])
38+
for (j in i + 1 until n) {
39+
if (nums[j] % nums[i] == 0) {
40+
val temp = listOf(nums[i]) + dfs(j)
41+
if (temp.size > res.size)
42+
res = temp
43+
}
44+
}
45+
46+
dp[i] = res
47+
return res
48+
}
49+
50+
var res = listOf<Int>()
51+
for (i in nums.indices) {
52+
val temp = dfs(i)
53+
if (temp.size > res.size)
54+
res = temp
55+
}
56+
57+
return res
58+
}
59+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy