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

前端 未结 30 2189
逝去的感伤
逝去的感伤 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:36

    The obvious solution is a function to map a digit to a list of keys, and then a function that would generate the possible combinations:

    The first is obvious, the second is more problematic because you have around 3^number of digits combinations, which can be a very large number.

    One way to do it is to look at each possibility for digit matching as a digit in a number (on base 4) and implement something close to a counter (jumping over some instances, since there are usually less than 4 letters mappable to a digit).

    The more obvious solutions would be nested loops or recursion, which are both less elegant, but in my opinion valid.

    Another thing for which care must be taken is to avoid scalability issues (e.g. keeping the possibilities in memory, etc.) since we are talking about a lot of combinations.

    P.S. Another interesting extension of the question would be localization.

提交回复
热议问题