[Leetcode]17. Letter combinations of a phone number keyboard combination

Source: Internet
Author: User

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.

Test instructions

Given a string of numbers, see how many of the corresponding letter strings.

Ideas:

Assumption:

The legitimacy of the string, does it contain a number 1? If so, how do I deal with it? Similarly, does the input consider * or #?

How does an empty string work?

In what order are multiple solutions returned?

With the interviewer walk through:

Take "All" for example:

When index = 0, pointing to ' 2 ' in "23"

String letters = "ABC"

For each char in letters,

Add to Path

Move index forward, pointing to ' 3 ' in "recursively", and the helper function to add every char to the path

Code:

1 classSolution {2     Private Staticstring[] Keyboard =3             Newstring[]{"", "", "abc", "Def",//' 0 ', ' 1 ', ' 2 ',...4"Ghi", "JKL", "MnO", "PQRS", "TUV", "WXYZ" };5     6      Publiclist<string> lettercombinations (String digits) {//"All"7list<string> result =NewArraylist<>();8         if(digits.length () = = 0)returnresult;9Helper (digits, 0, ""), result);Ten         returnresult;  One     } A      -     Private voidHelper (String digits,intIndex, String Path, list<string>result) { -         if(Index = =digits.length ()) { the result.add (path); -             return; -         } -          +String letters = Keyboard[digits.charat (index)-' 0 '];  -          for(inti = 0; I < letters.length (); i++ ){ +             Charc =Letters.charat (i); AHelper (digits, index+1, path+c, result); at         } -     } -}

[Leetcode]17. Letter combinations of a phone number keyboard combination

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.