Letter Combinations of a Phone Number

来源:互联网 发布:软件项目实施方案范文 编辑:程序博客网 时间:2024/05/16 23:55

Letter Combinations of a Phone Number

 Total Accepted: 51210 Total Submissions: 200367My Submissions

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.


class Solution {public:    vector<string> letterCombinations(string digits) {        vector<string> re;string str = "";char *tel[] = {"abc","def","ghi","jkl","mno","pqrs","tvu","wxyz"};int n = digits.length();if(!n)return re;Combination( re, str, tel, n,digits);return re;    }void Combination(vector<string> &re,string str,char * *tel,int n,string digits){if(n == 0){re.push_back(str);return;}else{string ori = str;char tmp = digits[digits.length() - n] - '2';if( tmp == 5 || tmp == 7) //4c次循环{for( int i = 0; i < 4; i ++){char ch = tel[tmp][i];str = ori + ch;Combination( re,str,tel,n-1,digits);}}else//3次循环{for( int i = 0; i < 3; i ++){char ch = tel[tmp][i];str = ori + ch;Combination( re,str,tel,n-1,digits);}}}}};


0 0
原创粉丝点击