Letter combinations of a Phone number--Leetcode

Source: Internet
Author: User

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.


Algorithm one: The combination of the thought of carrying the numeral.

Class Solution {public:vector<string> Lettercombinations (string digits) {const char *map[] = {"", "", "        ABC "," Def "," Ghi "," JKL "," MnO "," PQRS "," TUV "," WXYZ "};        int idx[sizeof (map)/sizeof (map[0]) = {0};        vector<string> result;        string item;        BOOL carry = false;                while (!carry) {item.clear ();                carry = true;                        for (int i=0; i<digits.size (); ++i) {const char * p = &map[digits[i]-' 0 '][idx[i]];                        if (*p) item.append (1, *p);                                if (carry && *p) {++idx[i];                                ++p;                                if (!*p) idx[i] = 0;                        else carry = false;      }} result.push_back (item);  } if (Result.empty ()) Result.push_back (item);    return result; }};

The following sentence is purely to satisfy the test case when the input of Leetcode is empty string (""):

        if (Result.empty ())                result.push_back (item);


See this algorithm execution time, can not help to do a, leave a memorial.


Algorithm two, to be continued


Letter combinations of a Phone number--Leetcode

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.