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"].
1.可以用递归+栈实现,时间O(n^3),空间O(n)
2.可以用遍历实现,时间O(n^3)
可以用STL实现,空间O(1)
可以用数组实现,空间O(n)
思路:例如"abc""def""ghi",先将"abc"拆成"a","b","c",再和"d""e""f"组合,组合的结果再和"g""h""i"组合
//
// start: combine letters from different strings
const alpha[10] =
{
" ", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"
}; // 给'0'赋空格,给'1'赋""
/************************************************************************/
/* method1:
DFS with stack and recusion */
/************************************************************************/
void dfs(vector<string> &result, string &str, string &digits, int current)
{
if(current == digits.length()) // 当前str中的个数满足所有digits都取了值
{
result.push_back(str);
return;
}
for(auto &a : alpha[digits[current]-'0']) // C++用法:通过auto来遍历string,从当前位开始到字符串结束,current控制哪一个字符串
{
str.push_back(a); // push当前字符
dfs(result, str, digits, current+1);// 递归
str.pop_back(); // pop出来,实现栈结构
}
}
vector<string>
letterCombinations_Recusion
(string digits)
{
vector<string> result;
string str;
dfs(result, str, digits, 0);
}
/************************************************************************/
/* method2.1:
DFS with iteration and recusion with STL */
/************************************************************************/
vector<string> letterCombinations_IterSTL(string digits)
{
vector<string> result(1, "");
for(auto d : digits)
{
const int n = result.size();
const int m = alpha[d-'0'].size();
result.resize(n*m);
for(int i = 0; i < m; i++)
copy(result.begin(), result.begin()+n, result.begin()+n*i); // copy(_first, _last, _dest) fisrt开始到lastcopy到dest起始
for(int i = 0; i < m; i++)
{
int begin = result.begin();
for_each(begin+n*i, begin+n*(i+1), [&](string &s))
s += alpha[d-'0'][i]; // 此时s即为result
}
}
return result;
}
/************************************************************************/
/* method2.2:
DFS with iteration and recusion with vectors */
/************************************************************************/
vector<string> letterCombinations_IterVector(string digits)
{
vector<string> result(1, "");
for(int i = 0; i < digits.size(); i++)
{
vector<string> tmp;
string str = alpha[digits[i]-'0'];
for(int j = 0; j < str.size(); i++)
{
for(int k = 0; k < result.size(); k++)// 取出当前已经组合好的结果,对新加入的单个元素进行组合
tmp.push_back(result[k]+str[j]);
}
result = tmp;
}
return result;
}
// end
//