
g0001_0100.s0051_n_queens.Solution.swift Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of leetcode-in-all Show documentation
Show all versions of leetcode-in-all Show documentation
104 LeetCode algorithm problem solutions
// #Hard #Top_100_Liked_Questions #Array #Backtracking #Big_O_Time_O(N!)_Space_O(N)
// #2024_06_23_Time_8_ms_(98.15%)_Space_16_MB_(94.44%)
public class Solution {
public func solveNQueens(_ n: Int) -> [[String]] {
var pos = [Bool](repeating: false, count: n + 2 * n - 1 + 2 * n - 1)
var pos2 = [Int](repeating: 0, count: n)
var ans = [[String]]()
helper(n, 0, &pos, &pos2, &ans)
return ans
}
private func helper(_ n: Int, _ row: Int, _ pos: inout [Bool], _ pos2: inout [Int], _ ans: inout [[String]]) {
if row == n {
construct(n, pos2, &ans)
return
}
for i in 0..
© 2015 - 2025 Weber Informatics LLC | Privacy Policy