Letter Combinations of a Phone Number

简介: Given a digit string, 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.

Given a digit string, 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.

Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

Note:
Although the above answer is in lexicographical order, your answer could be in any order you want.

参考:http://www.cnblogs.com/TenosDoIt/p/3771254.html

与LeetCode:Subsets I II 类似

 

C++实现代码:

#include<iostream>
#include<vector>
#include<string>
using namespace std;

class Solution {
public:
    vector<string> letterCombinations(string digits) {
        vector<string> ret(1,"");
        if(digits.empty())
            return ret;
        string str[]={" ","","abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"};
        size_t i,j,k;
        for(i=0;i<digits.size();i++)
        {
            string s=str[digits[i]-'0'];
            vector<string> tmp=ret;
            ret.clear();
            for(j=0;j<tmp.size();j++)
            {
                for(k=0;k<s.size();k++)
                    ret.push_back(tmp[j]+s[k]);
            }
        }
        return ret;
    }
};

int main()
{
    Solution s;
    vector<string> result=s.letterCombinations(string("31"));
    for(auto a:result)
        cout<<a<<endl;
}

 

相关文章
[LeetCode]--17. Letter Combinations of a Phone Number
Given a digit string, 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. Input:D
1324 0
LeetCode - 17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个数字串,输出其在手机九宫格键盘上的所有可能组合.
939 0
Letter Combinations of a Phone Number
手机按键组合,回溯 Letter Combinations of a Phone Number Given a digit string, return all possible letter combinations that the number could represent.
996 0
[LeetCode] Letter Combinations of a Phone Number
Well, a typical backtracking problem. Make sure you are clear with the following three problems: What is a partial solution and when is it finished?...
927 0
|
算法
Leetcode 313. Super Ugly Number
题目翻译成中文是『超级丑数』,啥叫丑数?丑数就是素因子只有2,3,5的数,7 14 21不是丑数,因为他们都有7这个素数。 这里的超级丑数只是对丑数的一个扩展,超级丑数的素因子不再仅限于2 3 5,而是由题目给定一个素数数组。与朴素丑数算法相比,只是将素因子变了而已,解法还是和朴素丑数一致的。
101 1
|
5月前
|
存储 SQL 算法
LeetCode 题目 65:有效数字(Valid Number)【python】
LeetCode 题目 65:有效数字(Valid Number)【python】