1.电话号码的字母组合
题目:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number
思路:
- 如果没有更多的数字需要被输入,那意味着当前的组合已经产生好了。
- 如果还有数字需要被输入:
- 遍历下一个数字所对应的所有映射的字母。
- 将当前的字母添加到组合最后,也就是 tmp = tmp + letter 。
- 重复这个过程,输入剩下的数字: backtrack(combination + letter, next_digits[1:])
- 参考此处理解:https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/solution/tong-su-yi-dong-dong-hua-yan-shi-17-dian-hua-hao-m/
class Solution {
public:
unordered_map<char,string> _map{
{'2',"abc"},{'3',"def"},{'4',"ghi"},{'5',"jkl"},
{'6',"mno"},{'7',"pqrs"},{'8',"tuv"},{'9',"wxyz"}
};
vector<string> letterCombinations(string digits) {
vector<string> res;
if(digits.empty()) return res;
dfs(digits,"",0,res);
return res;
}
void dfs(string digits, string cur, int index, vector<string>& res){
//1.递归出口
if(index==digits.size()){
res.push_back(cur);
}
for(int i=0; i<_map[digits[index]].size();i++){
cur.push_back(_map[digits[index]][i]); //临时结果压入一个字母
dfs(digits,cur,index+1,res); //以在当前位置压入该字母这一“情况”为前提,构造此“分支”的后续结果
cur.pop_back(); //状态还原,例如临时结果从 "ab" -> "a",下一次循环尝试"ac"
}
}
};
2.括号生成
题目:https://leetcode-cn.com/problems/generate-parentheses
思路:
- 当前左右括号都有大于 0 个可以使用的时候,才产生分支;
- 产生左分支的时候,只看当前是否还有左括号可以使用;
- 产生右分支的时候,还受到左分支的限制,右边剩余可以使用的括号数量一定得在严格大于左边剩余的数量的时候,才可以产生分支;
- 在左边和右边剩余的括号数都等于 0 的时候结算。
- 因为每一次尝试,都使用新的字符串变量,所以无需回溯
class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
if(n==0) return res;
dfs("",n,n,res);
return res;
}
void dfs(string s, int left, int right, vector<string>& res){
if(left==0 && right==0){
res.push_back(s);
return;
}
//剪枝(如图,左括号可以使用的个数严格大于右括号可以使用的个数,才剪枝,注意这个细节)
if(left>right){
return;
}
if(left>0){ //产生左分支,可用left-1
dfs(s+'(',left-1,right,res);
}
if(right>0){
dfs(s+')',left,right-1,res);
}
}
};
3.单词搜索
题目:https://leetcode-cn.com/problems/word-search
思路:
整体思路
使用深度优先搜索(DFS)和回溯的思想实现。关于判断元素是否使用过,我用了一个二维数组 mark 对使用过的元素做标记。
外层:遍历
首先遍历 board 的所有元素,先找到和 word 第一个字母相同的元素,然后进入递归流程。假设这个元素的坐标为 (i, j),进入递归流程前,先记得把该元素打上使用过的标记: mark[i][j] = true;
内层:递归
好了,打完标记了,现在我们进入了递归流程。递归流程主要做了这么几件事:
- 从 (i, j) 出发,朝它的上下左右试探,看看它周边的这四个元素是否能匹配 word 的下一个字母
- 如果匹配到了:带着该元素继续进入下一个递归
- 如果都匹配不到:返回 False
- 当 word 的所有字母都完成匹配后,整个流程返回 True
几个注意点
递归时元素的坐标是否超过边界
回溯标记 mark[i][j] = false 以及 return 的时机
class Solution {
public:
int dx[4]={-1,1,0,0};
int dy[4]={0,0,-1,1};
int m;
int n;
bool exist(vector<vector<char>>& board, string word) {
m=board.size();
n=board[0].size();
vector<vector<bool>> mark(m, vector<bool>(n,false));
for(int i=0; i<m;i++){
for(int j=0; j<n; j++){
if(dfs(board,i,j,0,word,mark)){
return true;
}
}
}
return false;
}
bool dfs(vector<vector<char>>& board, int i, int j, int u, string& word, vector<vector<bool>>& mark){
if(u==word.size()-1) return board[i][j]==word[u];
if(board[i][j]== word[u]){
mark[i][j]=true;
for(int k=0; k<4; k++){
int new_i=i+dx[k];
int new_j=j+dy[k];
if(inArea(new_i,new_j) && !mark[new_i][new_j]){
if(dfs(board, new_i, new_j, u+1, word, mark)){
return true;
}
}
}
mark[i][j]=false;
}
return false;
}
bool inArea(int x, int y) {
return x >= 0 && x < m && y >= 0 && y < n;
}
};
4. N皇后
题目:https://leetcode-cn.com/problems/n-queens
思路:
- 定义回溯函数(即深度优先搜索的递归函数)
void backTrack(vector<string>& board, int row, vector<vector<string>>& res)
首先我们需要传入棋盘状态 board, 我们需要不断的修改这个状态,也需要用这个状态来判断某位置是否可以放置皇后
然后,因为我们是一行一行搜索的,所以需要有参数row表示当前是哪一行。
最后,我们传入最终返回的结果集合的引用 vector<vector<string>>& res
- 成功退出条件
我们一行一行搜索,每搜索成功一行,将row+1并再次递归调用 backtrack 函数,因此当最后一行搜索成功后,row就等于N (row从0开始),只要判断 row==board.size()即可, 此时的棋盘状态已经成功放置了N个皇后。
if(row==board.size()){
res.push_back(board);
return;
}
- 核心搜索过程(剪枝+回溯)
for(int col=0; col<n; col++){
if(!isValid(board, row, col)){
continue;
}
board[row][col]='Q';
backTrack(board, row+1, res);
board[row][col]='.';
}
backtrack函数中我们针对当前row的每一列进行选择,首先要根据N皇后的规则进行剪枝,如果满足条件则棋盘当前位置(row,col)被放置上一个皇后,然后我们继续搜索下一层:backtrack(board, row+1, res); 这会在当前的状态下一直递归下去,直到成功或失败退出。无论是否成功,从此处的下一层调用返回本层后,我们撤销当前位置放置的皇后(回溯),然后选择下一列进行检测,如果位置有效,则继续向下一层搜索。
参考:https://leetcode-cn.com/problems/n-queens/solution/nhuang-hou-by-leetcode/ 图解理解一下递归过程
void backTrack(vector<string>& board, int row, vector<vector<string>>& res){
if(row==board.size()){
res.push_back(board);
return;
}
int n=board[row].size();
for(int col=0; col<n; col++){
if(!isValid(board, row, col)){
continue;
}
board[row][col]='Q';
backTrack(board, row+1, res);
board[row][col]='.';
}
}
- 关于isValid()函数
判断当前位置(row,col)是否有效,只需要在当前状态的基础上检查即可。因为是row从0开始向下搜索的,所以只需向上检查[0~row-1]的行中是否有和当前位置冲突的皇后。
bool isValid(vector<string>& board,int row, int col){
//检查同列
for(int i=0; i<row; i++){
if(board[i][col]=='Q'){
return false;
}
}
//左斜线
for(int i=row-1,j=col+1; i>=0 && j<board.size(); i--,j++){
if(board[i][j]=='Q') return false;
}
//右斜线
for(int i=row-1, j=col-1; i>=0 && j>=0; i--, j--){
if(board[i][j]=='Q'){
return false;
}
}
return true;
}
5. 复原IP地址
题目:https://leetcode-cn.com/problems/restore-ip-addresses/
思路:与上题类似
class Solution {
public:
vector<string> res;
vector<string> restoreIpAddresses(string s) {
int n = s.size();
string cur = s;
helper(n,0,-1,cur,s);
return res;
}
void helper(int n,int pointnum,int lastpoint,string& cur,string& s) {
//pointnum记录目前加了几个点了,lastpoint记录上一个点加的位置
if (pointnum == 3) {
//如果已经加了三个点了,并且最后一个点的右边表示的数小于255,则是正确IP地址
if (valid(lastpoint + 1,n-1,s)){
res.push_back(cur);
}
return;
}
//从上一个.号的下一个位置开始查找
for (int i = lastpoint + 1;i < n - 1;i++) {
//如果字符串s从上一个.号到i位置表示的数小于等于255,则符合条件
if (valid(lastpoint + 1,i,s)){
//正常回溯法,注意这里要+pointnum,因为已经加入的.号也会占位
cur.insert(cur.begin() + i + pointnum + 1,'.');
helper(n,pointnum + 1,i,cur,s);
cur.erase(pointnum + i + 1,1);
}
}
return;
}
bool valid(int left,int right,string& s) {
int sum = 0;
for (int i = left ;i <= right; i++) {
//处理0开头问题
if (left != right and s[left] == '0' ) return false;
//计算字符串s中left到right位表示的数的大小
sum = sum *10 + (s[i] - '0');
if (sum > 255) return false;
}
return true;
}
};