URL: https://leetcode.com/problems/letter-tile-possibilities/ Signed-off-by: Matej Focko <me@mfocko.xyz>
42 lines
1.1 KiB
Kotlin
42 lines
1.1 KiB
Kotlin
class Solution {
|
|
private fun factorial(n: Int): Int =
|
|
when {
|
|
n <= 1 -> 1
|
|
else -> (2..n).fold(1) { result, num -> result * num }
|
|
}
|
|
|
|
private fun permutations(seq: String): Int {
|
|
val freqs = IntArray(26) { 0 }
|
|
for (c in seq.toCharArray()) {
|
|
freqs[c - 'A']++
|
|
}
|
|
|
|
return freqs.filter {
|
|
it > 1
|
|
}.fold(factorial(seq.length)) { total, count ->
|
|
total / factorial(count)
|
|
}
|
|
}
|
|
|
|
private fun generate(
|
|
tiles: String,
|
|
seen: MutableSet<String>,
|
|
current: String,
|
|
i: Int,
|
|
): Int =
|
|
when {
|
|
i >= tiles.length && seen.add(current) -> permutations(current)
|
|
i >= tiles.length -> 0
|
|
else -> generate(tiles, seen, current, i + 1) + generate(tiles, seen, current + tiles[i], i + 1)
|
|
}
|
|
|
|
fun numTilePossibilities(tiles: String): Int {
|
|
val seen = mutableSetOf<String>()
|
|
|
|
val letters = tiles.toCharArray()
|
|
letters.sort()
|
|
val sortedTiles = String(letters)
|
|
|
|
return generate(sortedTiles, seen, "", 0) - 1
|
|
}
|
|
}
|