Leetcode: N-Queens

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.."]
]

vector nums(n);num[i]表示第i行的queen放在num[i]列,这样就转化成求0-n-1的全排列,然后看每一个排列是否符合条件。

vector> res;
	void permutationHelper(vector &nums, int index, int n)
	{
		if(index == n)
		{
			bool flag = true;
			for(int i = 0; i tmp;
				for(int i =0; i nums(n);
		for(int i = 0; i < n; i++)
			nums[i] = i;
		permutationHelper(nums,0,n);
	}
	vector > solveNQueens(int n) {
        // Note: The Solution object is instantiated only once.
        res.clear();
		permutation(n);
		return res;
    }





你可能感兴趣的:(Leetcode,算法与数据结构,程序员笔试面试)