那些年我们一起写过的代码3:回溯剪枝恢复现场

本文介绍了三道LeetCode编程题目:1.字母大小写全排列,使用深度优先搜索实现;2.优美的排列,涉及数论中的排列组合;3.N皇后问题,采用回溯法求解。
摘要由CSDN通过智能技术生成

1.784. 字母大小写全排列 - 力扣(LeetCode)

class Solution {
public:
vector<string>ret;
string path;
char sw(char a)
{
    if(a>='A'&&a<='Z')
    {
        return a+32;
    }
    return a-32;
}
void dfs(string s,int pos)
{
    if(pos==s.size())
    {
        ret.push_back(path);
        return;
    }
    path.push_back(s[pos]);
    dfs(s,pos+1);
    path.pop_back();
    if(s[pos]>='A'&&s[pos]<='Z'||s[pos]>='a'&&s[pos]<='z')
    {
char a=sw(s[pos]);
    path.push_back(a);
    dfs(s,pos+1);
    path.pop_back();
    }
}
    vector<string> letterCasePermutation(string s) {
 dfs(s,0);
 return ret;

    }
};

2.526. 优美的排列 - 力扣(LeetCode) (注意括号)

class Solution {
public:
int ret=0;
bool check[20]={false};

void dfs(int n,int pos)
{
    if(pos==n+1)
    {
        ret++;
        return;
    }
    for(int i=1;i<=n;i++)
{
    if(check[i]==false&&(pos%i==0||i%pos==0))
    {
        check[i]=true;

       dfs(n,pos+1);
       check[i]=false;
     
    }
}
}

    int countArrangement(int n) {
dfs(n,1);
return ret;
    }
};

3.51. N 皇后 - 力扣(LeetCode)


class Solution {  
public:  

vector<vector<string>>ret;
vector<string>path;
bool judge(vector<string>path,int row,int col,int n )
{
    for(int i=0;i<row;i++)
    {
        if(path[i][col]=='Q')
        {
            return false;
        }
    }
    for(int i=row-1,j=col-1;i>=0&&j>=0;i--,j--)
    {
        if(path[i][j]=='Q')
        {
            return false;
        }
    }
    for(int i=row-1,j=col+1;i>=0&&j<n;i--,j++)
    {
        if(path[i][j]=='Q')
        {
            return false;
        }
    }
    return true;
}
void dfs(int line,int n)
{
    if(line==n)
    {
        ret.push_back(path);
        return ;
    }
    for(int i=0;i<n;i++)
    {
        if(judge(path,line,i,n)==true)
        {
            path[line][i]='Q';
            dfs(line+1,n);
            path[line][i]='.';
        }
    }
}
  
    vector<vector<string>> solveNQueens(int n) {  
string good(n,'.');
path.resize(n,good);
dfs(0,n);
return ret;
    }  
};

  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值