File tree Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Expand file tree Collapse file tree 1 file changed +48
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution {
2+ fun minStickers (stickers : Array <String >, target : String ): Int {
3+ val stickCount = HashMap <String , MutableMap <Char , Int >>().apply {
4+ stickers.forEach { s ->
5+ this [s] = s.groupingBy { it }
6+ .eachCount()
7+ .toMutableMap()
8+ }
9+ }
10+
11+ val dp = HashMap <String , Int >()
12+
13+ fun dfs (t : String , stick : MutableMap <Char , Int >): Int {
14+ dp[t]?.let {
15+ return it
16+ }
17+
18+ var res = if (stick.isEmpty()) 0 else 1
19+ val remainT = StringBuilder ()
20+ for (c in t) {
21+ if (c in stick && stick[c]!! > 0 ) {
22+ stick[c] = stick[c]!! - 1
23+ } else {
24+ remainT.append(c)
25+ }
26+ }
27+
28+ if (remainT.length > 0 ) {
29+ val remainTS = remainT.toString()
30+ var used = Integer .MAX_VALUE
31+ for (s in stickCount.values) {
32+ if (remainTS[0 ]!! !in s)
33+ continue
34+ used = minOf(used, dfs(remainTS, s.toMutableMap()))
35+ }
36+
37+ dp[remainTS] = used
38+ res = if (used == Integer .MAX_VALUE ) Integer .MAX_VALUE else res + used
39+ }
40+
41+ return res
42+ }
43+
44+
45+ val res = dfs(target, mutableMapOf<Char , Int >())
46+ return if (res == Integer .MAX_VALUE ) - 1 else res
47+ }
48+ }
You can’t perform that action at this time.
0 commit comments