"""Pattern 18: Backtracking.

Build a candidate step by step: choose, recurse, un-choose. Prune a branch as
soon as it cannot lead to a valid answer. The generic shape:

    def backtrack(state):
        if is_complete(state):
            record(state); return
        for choice in choices(state):
            if valid(choice):
                make(choice); backtrack(state); undo(choice)
"""


def subsets(nums: list[int]) -> list[list[int]]:
    out: list[list[int]] = []
    path: list[int] = []

    def backtrack(start: int) -> None:
        out.append(path.copy())  # every node of the tree is a subset
        for i in range(start, len(nums)):
            path.append(nums[i])
            backtrack(i + 1)
            path.pop()

    backtrack(0)
    return out


def subsets_with_dup(nums: list[int]) -> list[list[int]]:
    """Sort, then skip a value equal to its left neighbour at the same depth."""
    nums = sorted(nums)
    out: list[list[int]] = []
    path: list[int] = []

    def backtrack(start: int) -> None:
        out.append(path.copy())
        for i in range(start, len(nums)):
            if i > start and nums[i] == nums[i - 1]:
                continue
            path.append(nums[i])
            backtrack(i + 1)
            path.pop()

    backtrack(0)
    return out


def permutations(nums: list[int]) -> list[list[int]]:
    out: list[list[int]] = []
    path: list[int] = []
    used = [False] * len(nums)

    def backtrack() -> None:
        if len(path) == len(nums):
            out.append(path.copy())
            return
        for i, x in enumerate(nums):
            if not used[i]:
                used[i] = True
                path.append(x)
                backtrack()
                path.pop()
                used[i] = False

    backtrack()
    return out


def combination_sum(candidates: list[int], target: int) -> list[list[int]]:
    """Each candidate may be reused: recurse with the same start index."""
    candidates = sorted(candidates)
    out: list[list[int]] = []
    path: list[int] = []

    def backtrack(start: int, remaining: int) -> None:
        if remaining == 0:
            out.append(path.copy())
            return
        for i in range(start, len(candidates)):
            if candidates[i] > remaining:
                break  # sorted, so every later candidate is too big as well
            path.append(candidates[i])
            backtrack(i, remaining - candidates[i])
            path.pop()

    backtrack(0, target)
    return out


def generate_parentheses(n: int) -> list[str]:
    out: list[str] = []

    def backtrack(path: str, opened: int, closed: int) -> None:
        if len(path) == 2 * n:
            out.append(path)
            return
        if opened < n:
            backtrack(path + "(", opened + 1, closed)
        if closed < opened:
            backtrack(path + ")", opened, closed + 1)

    backtrack("", 0, 0)
    return out


def solve_n_queens(n: int) -> list[list[str]]:
    """Track used columns and both diagonals in sets for O(1) validity checks."""
    out: list[list[str]] = []
    cols: set[int] = set()
    diag: set[int] = set()  # r - c
    anti: set[int] = set()  # r + c
    placement: list[int] = []

    def backtrack(r: int) -> None:
        if r == n:
            out.append(["." * c + "Q" + "." * (n - c - 1) for c in placement])
            return
        for c in range(n):
            if c in cols or r - c in diag or r + c in anti:
                continue
            cols.add(c)
            diag.add(r - c)
            anti.add(r + c)
            placement.append(c)
            backtrack(r + 1)
            cols.remove(c)
            diag.remove(r - c)
            anti.remove(r + c)
            placement.pop()

    backtrack(0)
    return out


def word_search(board: list[list[str]], word: str) -> bool:
    """Grid backtracking: mark a cell as used, explore, then restore it."""
    rows, cols = len(board), len(board[0])

    def dfs(r: int, c: int, i: int) -> bool:
        if i == len(word):
            return True
        if not (0 <= r < rows and 0 <= c < cols) or board[r][c] != word[i]:
            return False
        saved, board[r][c] = board[r][c], "#"
        found = any(dfs(r + dr, c + dc, i + 1) for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)))
        board[r][c] = saved
        return found

    return any(dfs(r, c, 0) for r in range(rows) for c in range(cols))
