【LeetCode】LeetCode——第17题:Letter Combinations of a Phone Number

17. Letter Combinations of a Phone Number

    My Submissions
Question Editorial Solution
Total Accepted: 78356  Total Submissions: 272852  Difficulty: Medium

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"].


















题目的大概意思是:给定一个数字字符串(数字为0-9),请按手机的9宫格输入法得到所有可能的字母组合(上面举了个列子)。

这道题难度等级:中等

思路:这个题看样子就是要用递归的节奏。先做一个索引表,将0-9的数字与其代表的字母对应起来,然后使用递归来做。

代码如下:

class Solution {
public:
    vector letterCombinations(string digits) {
		vector ans;
		if (digits.size() > 0){
			vector tmp = letterCombinations(digits.substr(1, digits.size() - 1));
			if (tmp.size() == 0){
				tmp.push_back("");
			}
			for (int i = 0; i < index[digits[0] - '0'].length(); ++i){
				for (int j = 0; j < tmp.size(); ++j){
					ans.push_back(index[digits[0] - '0'][i] + tmp[j]);
				}
			}
		}
		return ans;
    }
    vector index = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};//列表初始化
};
在这个代码中,倒数第二行的列表初始化是C++11.0以后的特性,现在的编译器可能有些不支持,想自己跑一下代码的得做一点点改动。

你可能感兴趣的:(LeetCode,LeedCode)