回溯法的核心思想:从一条路往前走,能进则进,不能进则退回来,换一条路再试。
letter-combinations-of-a-phone-number
题目描述
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> res;
if (digits.empty()) {
res.push_back("");
return res;
}
string dict[] = {"abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
letterCombinationsDFS(digits, dict, 0, "", res);
return res;
}
void letterCombinationsDFS(string digits, string dict[], int level, string out, vector<string> &res) {
if (level == digits.size()) res.push_back(out); //递归终止条件:dight中没有数字
else {
string str = dict[digits[level] - '2'];
for (int i = 0; i < str.size(); ++i) {
out.push_back(str[i]); //尝试一个一个的拼接
letterCombinationsDFS(digits, dict, level + 1, out, res);
out.pop_back(); //达到终止条件,退回另一条路
}
}
}
};
字符串的排列
输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路
链接:https://www.nowcoder.com/questionTerminal/fe6b651b66ae47d7acce78ffdd9a96c7
来源:牛客网
对于无重复值的情况
- 固定第一个字符,递归取得首位后面的各种字符串组合;
- 再把第一个字符与后面每一个字符交换,并同样递归获得首位后面的字符串组合;
- 递归的出口,就是只剩一个字符的时候,递归的循环过程,就是从每个子串的第二个字符开始依次与第一个字符交换,然后继续处理子串。
假如有重复值呢?
- 由于全排列就是从第一个数字起,每个数分别与它后面的数字交换,我们先尝试加个这样的判断——如果一个数与后面的数字相同那么这两个数就不交换了。
class Solution {
public:
vector<string> Permutation(string str) {
vector<string> res;
if (str.size() == 0) return res;
PermutationHelp(str, 0, str.size(), res);
sort(res.begin(), res.end());
return res;
}
void PermutationHelp(string &str, int begin, int size, vector<string> &res)
{
if (begin == size)
{
res.push_back(str); //递归的终止条件
}
else
{
for (int i = begin; i < size; i++)
{
if (begin != i && str[begin] == str[i])
continue; // 跳过重复的元素
swap(str[begin], str[i]); //交换
PermutationHelp(str, begin+1, size, res);//将剩下的元素排列
swap(str[begin], str[i]); //恢复原数组
}
}
}
};