51. N-Queens

problem description

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.

Example:

algorithm thought

经典的n皇后问题。使用回溯法解决问题,每次放之前首先判断这个位置是否合法,如果合法,放入这位置。如果不合法判断下个能放的位置。最后如果没有能放的位置的时候,就回溯。

code

algorithm analysis

这里的时间复杂度我也不是太清楚,查了资料,网上有两种说法,我觉得O(n^n)和O(n!)都有道理。

Last updated