N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法

N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

回溯法

百度百科:回溯法(探索与回溯法)是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步又一次选择,这样的走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

在包括问题的全部解的解空间树中,依照深度优先搜索的策略,从根结点出发深度探索解空间树。当探索到某一结点时,要先推断该结点是否包括问题的解,假设包括,就从该结点出发继续探索下去,假设该结点不包括问题的解,则逐层向其祖先结点回溯。(事实上回溯法就是对隐式图的深度优先搜索算法)。 若用回溯法求问题的全部解时,要回溯到根,且根结点的全部可行的子树都要已被搜索遍才结束。 而若使用回溯法求任一个解时,仅仅要搜索到问题的一个解就能够结束。


做完以下几题,应该会对回溯法的掌握有非常大帮助
N-Queens http://oj.leetcode.com/problems/n-queens/
N-Queens II   http://oj.leetcode.com/problems/n-queens-ii/
Generate Parentheses http://oj.leetcode.com/problems/generate-parentheses/


N-Queens

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens’ placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

For example,
There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

经典的八皇后问题的扩展,利用回溯法,

(1)从第一列開始试探性放入一枚皇后

(2)推断放入后棋盘是否安全,调用checkSafe()推断

(3)若checkSafe()返回true,继续放下一列,若返回false,回溯到上一列,又一次寻找安全位置

(4)遍历全然部位置,得到结果

class Solution {public:    vector<vector<string> > solveNQueens(int n) {        int *posArray = new int[n];        int count = 0;        vector< vector<string> > ret;          placeQueue(0, n, count, posArray, ret);        return ret;    }        //检查棋盘安全性    bool checkSafe(int row, int *posArray){        for(int i=0; i < row; ++i){            int diff = abs(posArray[i] - posArray[row]);                  if (diff == 0 || diff == row - i) {                       return false;              }          }        return true;    }        //放置皇后    void placeQueue(int row, int n, int &count, int *posArray, vector< vector<string> > &ret){        if(n == row){            count++;            vector<string> tmpRet;              for(int i = 0; i < row; i++){                  string str(n, '.');                  str[posArray[i]] = 'Q';                  tmpRet.push_back(str);              }              ret.push_back(tmpRet);            return;        }        //从第一列開始试探        for(int col=0; col<n; ++col){            posArray[row] = col;            if(checkSafe(row, posArray)){                 //若安全,放置下一个皇后                placeQueue(row+1, n, count, posArray, ret);            }        }    }};

N-Queens II

 

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

仅仅需计算个数count即可,略微改动

class Solution {public:    int totalNQueens(int n) {        int *posArray = new int[n];        int count = 0;        vector< vector<string> > ret;          placeQueue(0, n, count, posArray, ret);        return count;    }         //检查棋盘安全性    bool checkSafe(int row, int *posArray){        for(int i=0; i < row; ++i){            int diff = abs(posArray[i] - posArray[row]);                  if (diff == 0 || diff == row - i) {                       return false;              }          }        return true;    }        //放置皇后    void placeQueue(int row, int n, int &count, int *posArray, vector< vector<string> > &ret){        if(n == row){            count++;            return;        }        //从第一列開始试探        for(int col=0; col<n; ++col){            posArray[row] = col;            if(checkSafe(row, posArray)){                //若安全,放置下一个皇后                placeQueue(row+1, n, count, posArray, ret);            }        }    }};

Generate Parentheses

刚做完N-QUEUE问题,受之影响,此问题也使用回溯法解决,代码看上去多了非常多

class Solution {
public:
    vector<string> generateParenthesis(int n) {
       vector<string> vec; 
       int count = 0;
       int *colArr = new int[2*n];
       generate(2*n, count, 0, colArr, vec);
       delete[] colArr;
       return vec;
    }
    
    //放置括弧
    void generate(int n,int &count, int col, int *colArr, vector<string> &vec){
        if(col == n){
            ++count;
            string temp(n,'(');
            for(int i = 0;i< n;++i){
                if(colArr[i] == 1)
                    temp[i] = ')';
            }
            vec.push_back(temp);
            return;
        }
        for(int i=0; i<2;++i){
            colArr[col] = i;
            if(checkSafe(col, colArr, n)){
                //放置下一个括弧
                generate(n, count, col+1, colArr, vec);
            }
        }
    }
    
    //检查安全性
    bool checkSafe(int col, int *colArr, int n){
		int total = n/2;
        if(colArr[0] == 1) return false;
        int left = 0, right = 0;
        for(int i = 0; i<=col; ++i){
            if(colArr[i] == 0 )
                ++left;
            else 
                ++right;
        }
        if(right > left || left > total || right > total)
            return false;
        else
            return true;
    }
};

google了下,http://blog.csdn.net/pickless/article/details/9141935 代码简洁非常多,供參考

class Solution {
public:
    vector<string> generateParenthesis(int n) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<string> ans;
        getAns(n, 0, 0, "", ans);
        return ans;
    }

private:
    void getAns(int n, int pos, int neg, string temp, vector<string> &ans) {
        if (pos < neg) {
            return;
        }
        if (pos + neg == 2 * n) {
            if (pos == neg) {
                ans.push_back(temp);
            }
            return;
        }
        getAns(n, pos + 1, neg, temp + '(', ans);
        getAns(n, pos, neg + 1, temp + ')', ans);
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118294.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 安装python应该先安装pycharm还是python_Pycharm及python安装详细步骤及PyCharm配置整理(推荐)…「建议收藏」

    安装python应该先安装pycharm还是python_Pycharm及python安装详细步骤及PyCharm配置整理(推荐)…「建议收藏」首先我们来安装python1、首先进入网站下载:点击打开链接(或自己输入网址:https://www.python.org/downloads/),进入之后如下图,选择图中红色圈中区域进行下载。2、下载完成后如下图所示3、双击exe文件进行安装,如下图,并按照圈中区域进行设置,切记要勾选打钩的框,然后再点击Customizeinstallation进入到下一步:4、对于上图中,可以通过Brow…

    2022年8月28日
    6
  • pyttsx3 快速上手之:语音合成播报

    pyttsx3 快速上手之:语音合成播报Pythonpyttsx3使用之:语音播报pyttsx3是python中最常用的文字转语音库,使用方便,功能较为完整首先安装pyttsx3lib:pipinstallpyttsx3然后封装下API,实现为speaker.py:importpyttsx3global__speak_engine__speak_engine=Nonedefsay(content): global__speak_engine ifnot__speak_engine:

    2022年6月26日
    63
  • 安捷伦示波器使用说明书_安捷伦labview采集

    安捷伦示波器使用说明书_安捷伦labview采集Step1:配置VISA协议。VISA协议是AgilentIOLibraries的一部分,主要包含一个虚拟仪器软件架构VISA(一个比较通用的工业仪器软件架构)和标准控制库SICL.我理解前者相当一个底层架构,后者相当于一个指令集.先配置好VISA,然后通过SICL指令集发命令。直接上例子,简单明了。agilent示波器可以直接用VISA,所以只要在C++项目里进行配置。首先在C++里配…

    2022年10月12日
    1
  • web服务基础及web服务器搭建过程「建议收藏」

    web服务基础及web服务器搭建过程「建议收藏」当我们打开一个浏览器输入一个网站时,它会先找缓存再找hosts文件,如果缓存和hosts文件有相对应的地址的时候,就会直接拿到IP地址,(在互联网上计算机与计算机通信用的是IP,但IP地址太难记住为了方便我们人浏览网站就采用了字符串注入了域名的方式所以我们在打开网站输入地址的时候它首先就会做一个域名的解析工作)DNS架构:从后往前看…

    2022年5月8日
    58
  • mktime()函数使用「建议收藏」

    mktime()函数使用「建议收藏」原型:time_tmktime(structtm*)其中的tm结构体定义如下:structtm{inttm_sec;/*秒–取值区间为[0,59]*/inttm_min

    2022年8月6日
    9
  • jQuery ajax()使用serialize()提交form数据

    jQuery ajax()使用serialize()提交form数据

    2021年10月31日
    47

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号