How can I print out all possible letter combinations a given phone number can represent?

前端 未结 30 2232
逝去的感伤
逝去的感伤 2020-12-22 18:01

I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations

30条回答
  •  天命终不由人
    2020-12-22 18:39

    Scala solution:

    def mnemonics(phoneNum: String, dict: IndexedSeq[String]): Iterable[String] = {
      def mnemonics(d: Int, prefix: String): Seq[String] = {
        if (d >= phoneNum.length) {
          Seq(prefix)
        } else {
          for {
            ch <- dict(phoneNum.charAt(d).asDigit)
            num <- mnemonics(d + 1, s"$prefix$ch")
          } yield num
        }
      }
    
      mnemonics(0, "")
    }
    

    Assuming each digit maps to at most 4 characters, the number of recursive calls T satisfy the inequality T(n) <= 4T(n-1), which is of the order 4^n.

提交回复
热议问题