Letter Combinations of a Phone Number (Medium)
问题描述
题目大致的意思是,手机九宫格键盘,输入几个数字,列出输出字母的所有可能,即 排列组合
Examples
Input
"23"
Output
["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]
算法思路
这题也是想了一会,马上就想到了 dsf 中的 回溯 思想,用回溯算法解起来会相当方便, dfs深度遍历 思路如下
每个输入数字对应 一排 输出可能,每排的顺序按输入数字的顺序由上至下
由上至下 遍历,每次都摘取一个字母
当遍历到底部时,此时摘取的字符串便是排列组合中的一种可能,然后开始回溯向上
AC 代码
void dfs(string digits,
vector<string> &result,
string maps[][4],
string str) {
// reach the buttom
if (digits.size() == 0) {
result.push_back(str);
return;
}
int num = digits[0] - '0';
for (int j = 0; j < 4; j++) {
string temp = maps[num][j];
// the end of map
if (temp == "-1") {
break;
}
// pick one from this line
str.append(temp);
// next line
dfs(digits.substr(1, digits.size() - 1), result, maps, str);
str.erase(str.end() - 1);
}
}
vector<string> letterCombinations(string digits) {
vector<string> result;
if (digits == "") {
return result;
}
string maps[][4] = {
{" ", "-1"},
{"-1"},
{"a", "b", "c", "-1"},
{"d", "e", "f", "-1"},
{"g", "h", "i", "-1"},
{"j", "k", "l", "-1"},
{"m", "n", "o", "-1"},
{"p", "q", "r", "s"},
{"t", "u", "v", "-1"},
{"w", "x", "y", "z"}
};
string str;
dfs(digits, result, maps, str);
return result;
}
Generate Parentheses (Medium)
问题描述
输入一个数 n,求合法的 n 对 括号 所有组合方式
Examples
Input
3
Output
[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]
算法思路
所有的排列组合问题,应该都是用 回溯 算法解,此题唯一不同的点在于,如何巧妙的实现括号 合法排列,其实只要能保证再回溯前,左括号的添加在右括号之前,就能到达这一要求,详尽的看代码
AC 代码
void dfs(vector<string> &result,
string str,
int leftNum,
int rightNum,
int n) {
if (str.size() == 2 * n) {
// reaches
result.push_back(str);
return;
}
if (leftNum < n) {
// append left parenthesis on back-track firstly
dfs(result, str + "(", leftNum + 1, rightNum, n);
}
// left parenthesis must be more than right parenthesis
if (rightNum < leftNum) {
// append right parenthesis on back-track secondly
dfs(result, str + ")", leftNum, rightNum + 1, n);
}
}
vector<string> generateParenthesis(int n) {
vector<string> result;
string str;
dfs(result, str, 0, 0, n);
return result;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。