[C + +] Leetcode:87 letter combinations of a Phone number

Source: Internet
Author: User
Tags first string

Title:

Given a digit string, return all possible letter combinations, the number could represent.

A mapping of Digit to letters (just as on the telephone buttons) is given below.

Input: Digit string "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.

Answer 1: Recursive method (DFS)

idea: We follow the number of digits of the number string, one by one DFS disassembly. After the first corresponding letter is obtained, the DFS search continues until the number of digits is reached. Add this result and return.

Attention:

1. How to initialize a numeric alphabetic lookup table, represented by an array of strings. The string array one-dimensional coordinates represent the position to the first string, and the two-dimensional coordinates represent the position to the character. e.g. numap[3][2] = ' f '

String numap[] = {"", "" "," abc "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "};
2. Note that when digits is empty, we return "" instead of an empty array.

String Tmpstr (Digits.size (), ');
3. If we apply the first letter of the number 2 at this time, how can we subtly replace the other letters of the number 2 after DFS? If we push and then pop, we can only pop the last character, can not accurately locate, and produce incorrect results. Here we use index to replace the new letters. (index indicates the calculation of digits)

Tmpstr[index] = numap[digits[index]-' 0 '][i];
Using pop to produce incorrect results: Tmpstr.pop_back ();

Input: "2"
Output: ["A", "B", "C"]
Expected: ["A", "B", "C"]
Submitted Code

AC Code:

Class Solution {public:    vector<string> lettercombinations (string digits) {        vector<string> ret;  if (digits.size () = = 0) return ret;        String Tmpstr (Digits.size (), ');        Lettercombinations_helper (digits, 0, TMPSTR, ret);        return ret;    }    Private:    vector<vector<char> > phonetable;    void Lettercombinations_helper (string digits, int index, String tmpstr, vector<string>& ret)    {        String numap[] = {"", "" "," abc "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "};        if (index = = digits.size ())        {            ret.push_back (TMPSTR);            return;        }        for (int i = 0; i < Numap[digits[index]-' 0 '].size (); i++)        {            Tmpstr[index] = numap[digits[index]-' 0 '][i];
   lettercombinations_helper (digits, index+1, TMPSTR, ret);           Tmpstr.pop_back ();        }                return;}    };

Answer 2: Non-recursive method (BFS)

Idea: We follow the number of digits, iterative to solve the results, first from all the possible start, and continuously expand the results. The idea is somewhat similar to seeking subset.

For example, we require "23", Initialize RET = [""], 2 corresponds to three letters, so TMP will push three times, get tmp[0] = "" + ' a '; TMP[1] = "" + ' B '; TMP[2] = "" + ' C '. RET = tmp; (The first outermost iteration ends); ret.size () = 3. Tmp[0] = "a" + ' d '; TMP[1] = "a" + ' e '; TMP[2] = "a" + ' F '; TMP[3] = "B" + ' d '; ..... Until you get all the results. (The end of the outer iteration). Every time you update all the results of a RET so far, the next iteration will add more possibilities on that basis.

This method may be somewhat difficult to understand, not quite in line with the normal thinking process, but can expand programming ideas.

Attention: Three-layer loop, outermost: digits (digits.size ()); Second layer: The number of subsets within the current ret (ret.size ()); The inner layer: all possible letters of this number (Numap[digits[i]-' 0 '].size ()). is the BFS idea.

AC Code:

Class Solution {public:    vector<string> lettercombinations (string digits) {        vector<string> ret (1, "");        String numap[] = {"", "" "," abc "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "};                for (int i = 0; i < digits.size (); i++)        {            vector<string> tmp;                        for (int j = 0; J < Ret.size (); j + +)            {for                (int k = 0; k < numap[digits[i]-' 0 '].size (); k++)                {                    Tmp.pu Sh_back (Ret[j] + numap[digits[i]-' 0 '][k]);                }            }            UPDATE ret            ret = tmp;        }                return ret;    }};





Submitted: minutes ago
Input: "2"
Output: ["A", "B", "C"]
Expected: ["A", "B", "C"]
Submitted Code

[C + +] Leetcode:87 letter combinations of a Phone number

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.