17. Letter Combinations of a Phone Number

leetcode

Posted by chl on May 16, 2019

题目

Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

A mapping of digit to letters (just like on the telephone buttons) is given below. Note that 1 does not map to any letters.
image

题意

给定一个数字字符串S,根据图中的每个数字对应的字母表,求出该s所有可能的字母组合

例子

Input: “23”
Output: [“ad”, “ae”, “af”, “bd”, “be”, “bf”, “cd”, “ce”, “cf”].

题解

求组合。将每个数字对应的字母表用map存储,然后根据s一个一个对应的求组合。

代码

var ans []string
var letter = map[byte]string{
    '2':"abc",
    '3':"def",
    '4':"ghi",
    '5':"jkl",
    '6':"mno",
    '7':"pqrs",
    '8':"tuv",
    '9':"wxyz",
}
func letterCombinations(digits string) []string {
    if len(digits)==0{
        return nil
    }
    
    ans = make([]string,0)
    temp := ""
    combina(digits,temp,0)
    return ans
}

func combina(digits ,temp string,n int){
    if len(temp)==len(digits){
        ans = append(ans,temp)
        return
    }
    
    for _,v := range letter[digits[n]]{
        temp +=string(v)
        combina(digits,temp,n+1)
        temp = temp[:len(temp)-1]
    }
    return
}

总结

简单题目,套用求组合的解法就ok了。
rune 也可以直接string()转字符串。