|
| 1 | +package kotlin |
| 2 | + |
| 3 | +class Solution { |
| 4 | + fun letterCombinations(digits: String): List<String> { |
| 5 | + if (digits.isEmpty()) return emptyList() |
| 6 | + val resultantList = mutableListOf<String>() |
| 7 | + val stringBuilder = StringBuilder() |
| 8 | + val digitCharListMapping = mutableMapOf( |
| 9 | + '2' to listOf('a', 'b', 'c'), |
| 10 | + '3' to listOf('d', 'e', 'f'), |
| 11 | + '4' to listOf('g', 'h', 'i'), |
| 12 | + '5' to listOf('j', 'k', 'l'), |
| 13 | + '6' to listOf('m', 'n', 'o'), |
| 14 | + '7' to listOf('p', 'q', 'r', 's'), |
| 15 | + '8' to listOf('t', 'u', 'v'), |
| 16 | + '9' to listOf('w', 'x', 'y', 'z') |
| 17 | + ) |
| 18 | + |
| 19 | + fun dfs(decisionIndex: Int = 0) { |
| 20 | + if (stringBuilder.length == digits.length) { |
| 21 | + resultantList.add(stringBuilder.toString()) |
| 22 | + return |
| 23 | + } |
| 24 | + val charListForDigitAtDecisionIndex = digitCharListMapping.getValue(digits[decisionIndex]) |
| 25 | + for (char in charListForDigitAtDecisionIndex) { |
| 26 | + stringBuilder.append(char) |
| 27 | + dfs(decisionIndex + 1) |
| 28 | + stringBuilder.deleteCharAt(stringBuilder.lastIndex) |
| 29 | + } |
| 30 | + } |
| 31 | + dfs() |
| 32 | + return resultantList |
| 33 | + } |
| 34 | +} |
0 commit comments