17. *的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

 

示例:

输入:"23"
输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

/*
解题思路:
我们需要建立一个字典,用来保存每个数字所代表的字符串,然后我们还需要一个变量 level,
记录当前生成的字符串的字符个数,实现套路和上述那些题十分类似。在递归函数中我们首先判断 level,
如果跟 digits 中数字的个数相等了,我们将当前的组合加入结果 res 中,然后返回。
否则我们通过 digits 中的数字到 dict 中取出字符串,然后遍历这个取出的字符串,
将每个字符都加到当前的组合后面,并调用递归函数即可
*/
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Solution 
{
public:
	vector<string> letterCombinations(string digits) 
	{
		if (digits.empty()) 
			return{};
		vector<string> res{ "" };
		vector<string> dict{ "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };
		for (int i = 0; i < digits.size(); ++i)
		{
			vector<string> t;
			string str = dict[digits[i] - '0'];
			for (int j = 0; j < str.size(); ++j) 
			{
				for (string s : res) 
					t.push_back(s + str[j]);
			}
			res = t;
		}
		return res;
	}
};
int main()
{
    string str;
	cin >> str;
	vector<string>t = Solution().letterCombinations(str);
	for (int i = 0; i < t.size(); i++)
		cout << t[i]<<" ";
	system("pause");
	return 0;
}

  

原文地址:https://www.cnblogs.com/277223178dudu/p/11402828.html