https://leetcode.com/problems/letter-combinations-of-a-phone-number/
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.
Example:
Input: "23" Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
用个dictionary把数字和字母映射,然后recursion tree每层选一个字母,dfs
class Solution(object):
def letterCombinations(self, digits):
if not digits:
return []
dic = {"2":"abc", "3":"def", "4":"ghi", "5":"jkl", "6":"mno", "7":"pqrs", "8":"tuv", "9":"wxyz"}
res=[]
self.helper(0,digits,dic,res,[])
return res
def helper(self,index,digits,dic,res,cur):
if len(cur)==len(digits):
res.append("".join(cur))
return
for i in dic[digits[index]]:
self.helper(index+1,digits,dic,res,cur+[i])