Clean recusrsive Scala solution


  • 0
    M

    It is possible to make the recursive call tail recursive(@tailrec), but that needs refactoring and leads to a longer solution.

    
    object Solution {
        val mapping = Map[Char, List[String]](
            '1' -> List.empty[String],
            '2' -> List("a", "b", "c"),
            '3' -> List("d", "e", "f"),
            '4' -> List("g", "h", "i"),
            '5' -> List("j", "k", "l"),
            '6' -> List("m", "n", "o"),
            '7' -> List("p", "q", "r", "s"),
            '8' -> List("t", "u", "v"),
            '9' -> List("w", "x", "y", "z"),
            '0' -> List.empty[String]
        )
    
        def letterCombinations(digits: String): List[String] = {
            if (digits.isEmpty) {
                List.empty[String]
            } else if (digits.size == 1) {
                mapping(digits.head)
            } else {
                for (prefix <- mapping(digits.head); suffix <- letterCombinations(digits.tail))
                    yield prefix + suffix
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.