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.

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);
}
};
N-Queens And N-Queens II [LeetCode] + Generate Parentheses[LeetCode] + 回溯法的更多相关文章
- 22. Generate Parentheses C++回溯法
把左右括号剩余的次数记录下来,传入回溯函数. 判断是否得到结果的条件就是剩余括号数是否都为零. 注意判断左括号是否剩余时,加上left>0的判断条件!否则会memory limited erro ...
- Generate Parentheses - LeetCode
目录 题目链接 注意点 解法 小结 题目链接 Generate Parentheses - LeetCode 注意点 解法 解法一:递归.当left>right的时候返回(为了防止出现 )( ) ...
- LeetCode: Generate Parentheses 解题报告
Generate ParenthesesGiven n pairs of parentheses, write a function to generate all combinations of w ...
- [LeetCode]Generate Parentheses题解
Generate Parentheses: Given n pairs of parentheses, write a function to generate all combinations of ...
- LeetCode刷题笔记-回溯法-括号生成
题目描述: 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合. 例如,给出 n = 3,生成结果为: [ "((()))", "( ...
- LeetCode刷题笔记-回溯法-分割回文串
题目描述: 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. 示例: 输入: "aab"输出:[ ["aa", ...
- [LeetCode] Generate Parentheses 生成括号
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
- Generate Parentheses leetcode java
题目: Given n pairs of parentheses, write a function to generate all combinations of well-formed paren ...
- Generate Parentheses——LeetCode
Given n pairs of parentheses, write a function to generate all combinations of well-formed parenthes ...
随机推荐
- JS - 删除确认
<a href="javascript:if(confirm('确实要删除吗?'))location='<{:U('Admin/Update/deleteuserinfo', a ...
- C++,对象的 =赋值 以及 复制构造函数赋值
1. C++默认实现了 = 号赋值:operator=只要将一个对象的内容的内容逐位复制给另外一个对象即可. 2. C++默认实现了复制构造函数:同样,只要将一个对象的内容的内容逐位复制给另外一个对象 ...
- Android的WiFi开启与关闭
注意:要首先注册开启和关闭WiFi的权限, <?xml version="1.0" encoding="utf-8"?> <manifest ...
- 【集训笔记】二分图及其应用【HDOJ1068【HDOJ1150【HDOJ1151
匈牙利算法样例程序 格式说明 输入格式: 第1行3个整数,V1,V2的节点数目n1,n2,G的边数m 第2-m+1行,每行两个整数t1,t2,代表V1中编号为t1的点和V2中编号为t2的点之间有边相连 ...
- 应用程序无法正常启动0xc000007b
参考: http://jingyan.baidu.com/article/ff42efa9181bbbc19e22022f.html DirectX修复工具: http://blog.csdn.net ...
- SystemTap----将SystemTap脚本编译成内核模块
当运行SystemTap脚本时,会根据脚本生成一个内核模块,然后插入到系统中执行后退出.这个过程总共分为5个阶段:parse, elaborate, translate, compile, run ...
- Linux 下IOport编程訪问
曾经写的一篇笔记.偶尔翻出来了,放在这里做个纪念 Linux 下IOport编程訪问 这里记录的方法是在用户态訪问IOport,不涉及驱动程序的编写. 首先要包括头文件 /usr/include/as ...
- Qt持久性对象进行序列化(同时比较了MFC与Java的方法)
Mfc和Java中自定义类的对象都可以对其进行持久性保存,Qt持久性对象进行序列化当然也是必不可少的.不过这个问题还真困扰了我很长时间……Mfc通过重写虚函数Serialize().Java则是所属的 ...
- QTableWidget 导出到csv表格
跳槽到了新的公司,开始苦逼的出差现场开发,接触到了新的应用.有很多应用需要将Table导出成表格,可以把table导出成csv格式的文件.跟大伙分享一下: lass TableToExcle : pu ...
- hdu 5015 大数量反复类似操作问题/ 矩阵高速幂
题意: 给一个矩阵a,第一行是 0. 233,2333,23333.....第一列读入.列数<10^9.行数<=10. 先转化操作: m是大数量.必定每次向前推一列.就是每次乘一个矩阵T. ...