Leetcode algorithm Problem python solution: 17. Letter combinations of a Phone number

Source: Internet
Author: User
Tags generator

Topic:

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

A mapping of Digit to letters (just as on the telephone buttons) is given below. Note that 1 does is not a map to any letters.

Example:

Input: "Output": ["ad", "AE", "AF", "BD", "Be", "BF", "CD", "CE", "CF"].

Note:

Although the above answer is in lexicographical order, your answer could are in any order you want.

This question translates into Chinese is actually relatively simple, is gives you the number, lets you output the numeral map the letter all may appear the combination situation. Letters that are mapped to the same number are not grouped together, not in alphabetical order, and each letter combination must contain one letter for all numeric mappings.

Here the use of recursion can be easily solved, just recently saw some generator related information, simply use recursive generator, more concise and convenient.

The code is as follows:

1 classSolution:2     deflettercombinations (self, digits):3         returnlist (self.recur (digits))
4 defrecur (self, x): #由于LeetCode验证代码时不会自动将生成器转化为列表, so only the generator is written outside, the main function only prints the answer 5DIC = {'2':'ABC','3':'def','4':'Ghi','5':'JKL','6':'MnO','7':'PQRS','8':'TUV','9':'WXYZ'}6 ifLen (x) = =0: #将digits为空值拿出来特别处理7 return []8 forIinchDic[x[0]]:9 ifLen (x) = = 1: #递归到digits只剩最后一个值挨个生成该值的映射Ten yieldI One Else: A forJinchSelf.lettercombinations (x[1:]): #这里返回的生成器, can be used to iterate - yieldi + j#拼接字符串, return one layer at a

Leetcode algorithm Problem python solution: 17. Letter combinations of a Phone number

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.