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

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

    A Python solution is quite economical, and because it uses generators is efficient in terms of memory use.

    import itertools
    
    keys = dict(enumerate('::ABC:DEF:GHI:JKL:MNO:PQRS:TUV:WXYZ'.split(':')))
    
    def words(number):
        digits = map(int, str(number))
        for ls in itertools.product(*map(keys.get, digits)):
            yield ''.join(ls)
    
    for w in words(258):
        print w
    

    Obviously itertools.product is solving most of the problem for you. But writing it oneself is not difficult. Here's a solution in go, which is careful to re-use the array result to generate all solutions in, and a closure f to capture the generated words. Combined, these give O(log n) memory use inside product.

    package main
    
    import (
        "bytes"
        "fmt"
        "strconv"
    )
    
    func product(choices [][]byte, result []byte, i int, f func([]byte)) {
        if i == len(result) {
            f(result)
            return
        }
        for _, c := range choices[i] {
            result[i] = c
            product(choices, result, i+1, f)
        }
    }
    
    var keys = bytes.Split([]byte("::ABC:DEF:GHI:JKL:MNO:PQRS:TUV:WXYZ"), []byte(":"))
    
    func words(num int, f func([]byte)) {
        ch := [][]byte{}
        for _, b := range strconv.Itoa(num) {
            ch = append(ch, keys[b-'0'])
        }
        product(ch, make([]byte, len(ch)), 0, f)
    }
    
    func main() {
        words(256, func(b []byte) { fmt.Println(string(b)) })
    }
    

提交回复
热议问题