LeetCode052——N皇后II

版权声明:版权所有,转载请注明原网址链接。 https://blog.csdn.net/qq_41231926/article/details/82796011

我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/n-queens-ii/description/

题目描述:

知识点:递归、回溯

思路:采用回溯法穷尽所有不同的n皇后问题的解决方案

本题和LeetCode051——N皇后完全相同,甚至更简单。因为我们不需要求出所有解决方案,只需要求出不同解决方案的数量即可。

只需要将LeetCode051——N皇后中保存结果的过程改为令结果result++即可。

时间复杂度依然是O(n ^ n)级别的,空间复杂度依然是O(n ^ 3)级别的。

JAVA代码:

public class Solution {

	int result;
	
	public int totalNQueens(int n) {
		boolean[][] visited = new boolean[n][n];
		totalNQueens(new HashMap<>(), 0, n, visited);
		return result;
	}
	
	/*
	 * hashMap-------The queen in row key is in column value
	 * we are going to put the mth queen
	 * n represents the total quantity of the queen
	 */
	private void totalNQueens(HashMap<Integer, Integer> hashMap, int m, int n, boolean[][] visited) {
		if(m == n) {
			result++;
			return;
		}
		for (int i = 0; i < n; i++) {
			if(!visited[m][i]) {
				hashMap.put(m, i);
				boolean[][] tempVisited = new boolean[n][n];
				for (int j = 0; j < n; j++) {
					for (int k = 0; k < n; k++) {
						tempVisited[j][k] = visited[j][k];
					}
				}
				for (int j = 0; j < n; j++) {
					tempVisited[j][hashMap.get(m)] = true;
					tempVisited[m][j] = true;
					for (int k = 0; k < n; k++) {
						if((Math.abs(j - m) == Math.abs(k - hashMap.get(m)))) {
							tempVisited[j][k] = true;
						}
					}
				}
				totalNQueens(hashMap, m + 1, n, tempVisited);
				hashMap.remove(m);
			}
		}
	}
}

LeetCode解题报告:

猜你喜欢

转载自blog.csdn.net/qq_41231926/article/details/82796011