class Solution { fun isSolvable(words: Array<String>, result: String): Boolean { val map = HashMap<Char, Int>() val firstChar = HashSet<Char>() for (word in words) { firstChar.add(word[0]) word.forEachIndexed { index, c -> map[c] = map.getOrDefault(c, 0) + 10.0.pow(word.length - 1 - index).toInt() } } firstChar.add(result[0]) result.forEachIndexed { index, c -> map[c] = map.getOrDefault(c, 0) - 10.0.pow(result.length - 1 - index).toInt() } val usedChar = map.keys.toMutableList() return dfs(map, firstChar, usedChar, BooleanArray(10), 0) }
fun dfs(map: HashMap<Char, Int>, firstChar: HashSet<Char>, usedChar: MutableList<Char>, usedDigits: BooleanArray, sum: Int): Boolean { if (usedChar.isEmpty()) return sum == 0 val c = usedChar.removeAt(0) for (i in 0..9) { if (usedDigits[i]) continue if (i == 0 && firstChar.contains(c)) continue usedDigits[i] = true if (dfs(map, firstChar, usedChar, usedDigits, sum + map.getOrDefault(c, 0) * i)) return true usedDigits[i] = false } usedChar.add(0, c) return false } }