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

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

    I am rather a newbie so please correct me wherever I am wrong.

    First thing is looking into space & time complexity. Which is really bad since it's factorial so for factorial(7) = 5040 any recursive algorithm would do. But for factorial(12) ~= 4 * 10^8 which can cause stack overflow in recursive solution.

    So I would not attempt a recursive algorithm. Looping solution is very straight forward using "Next Permutation".

    So I would create and array {0, 1, 2, 3, 4, 5} and generate all permutation and while printing replace them with respective characters eg. 0=A, 5=F

    Next Perm algorithm works as follows. eg Given 1,3,5,4 next permutation is 1,4,3,5

    Steps for finding next perm.

    1. From right to left, find first decreasing number. eg 3

    2. From left to right, find lowest number bigger than 3 eg. 4

    3. Swap these numbers as reverse the subset. 1,4,5,3 reverse subset 1,4,3,5

    Using Next permutation ( or rotation) you generate specific subset of permutations, say you want to show 1000 permutations starting from a particular phone number. This can save you from having all numbers in memory. If I store numbers as 4 byte integers, 10^9 bytes = 1 GB !.

提交回复
热议问题