The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

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.."] ]
 bool nextPermutation(vector<int> &num)
{
	int i = num.size() - 1;
	while (i >= 1)
	{
		if(num[i] > num[i - 1])
		{
			--i;
			int ii = num.size() - 1;
			while (ii > i && num[ii] <= num[i]) --ii;
			if(ii > i)
			{
				swap(num[i], num[ii]);
				reverse(num.begin() + i + 1, num.end());
				return true;
			}
		}
		else
			--i;
	}
    return false;
}
bool check(vector<int> &grids)
{
	int len = grids.size();
	for (int i = 0; i < len; ++i)
		for (int j = i + 1; j < len; ++j)
		{
			if(abs(i - j) == abs(grids[i] - grids[j]))
				return false;
		}
	return true;
}
vector<vector<string> > solveNQueens(int n) {
	vector<vector<string> > re;
	if(n < 1)
		return re;
	if(n == 1)
	    return vector<vector<string> >(1,vector<string>(1,"Q"));
	vector<int> grids(n,0);
	for (int i = 0; i < n; ++i)
	{
		grids[i] = i;
	}
	while (nextPermutation(grids))
	{
		if(check(grids))
		{
			vector<string> one_solve;
			for(int i = 0; i < n; ++i)
			{
				string line(n,'.');
				line[grids[i]] = 'Q';
				one_solve.push_back(line);
			}
			re.push_back(one_solve);
		}
	}
	return re;
}【leetcode】N-queens,布布扣,bubuko.com
原文地址:http://blog.csdn.net/shiquxinkong/article/details/27965783