Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailIniziaDownloadDocumentazioneAcquistaTutti i prodotti
Marketplace
Notizie
TecnologiaNotizieNotizie di sviluppo di oggiDocumentazioneLinguaggi di programmazioneRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFramework frontend webNext.jsReactVue.js · NuxtSvelteKitAngularFramework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFramework per app e desktopTauriFlutterReact NativeElectronAlgoritmiBasi degli algoritmiAlgoritmi fondamentaliAlgoritmi avanzatiAlgoritmi pratici
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrinaGuida alla community
CollaboraTrasferimento tecnicoRealizzazione del sito webRealizzazione di app desktopPipeline di rilascio e pagamentoPartner commercialeContatti
ServiziDesktop remotoPacchetti di installazione su misura
TASTEDEV
Prodotti

Strumenti desktop

TASTECADApri con leggerezza anche i disegni più complessiTASTEFILESSolo i file che servono, alla massima velocitàTASTEFTPLa via più ordinata per i tuoi fileTASTESSHUn legame più solido tra te e i tuoi serverTASTEZIPComprimi più veloce, estrai più sicuro

Strumenti per sviluppatori

TASTECODEModifica, compila, esegui il debug e testa app Rust in un'unica finestraTASTESTUDIODalla modifica ai test remoti e alle correzioni IA approvateTASTEETLSposta i dati guardando i valori

Server

TASTEREMOTEUn desktop remoto che gira sul tuo serverTASTEGEOUn server geospaziale compatibile con GeoServer, ricostruito in RustTASTEMAILRiprendi il controllo della tua posta

Inizia

DownloadUltime versioni di ogni prodottoDocsCome usare ogni prodottoAcquistaAbbonamenti e licenze perpetueTutti i prodottiTutti i prodotti a colpo d’occhio
Tutti i prodotti
MarketplaceNotizie
Tecnologia

Notizie

Notizie di sviluppo di oggiAnnunci ufficiali su linguaggi, framework, GitHub e IADocumentazioneGuide a linguaggi, framework e algoritmi

Linguaggi di programmazione

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Framework

Framework frontend webNext.jsReactVue.js · NuxtSvelteKitAngular
Framework serverSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Framework per app e desktopTauriFlutterReact NativeElectron

Algoritmi

Basi degli algoritmiAnalisi della complessità · Ordinamento · Ricerca · Strutture dati di base · Alberi e heapAlgoritmi fondamentaliVisita dei grafi · Cammini minimi e alberi ricoprenti · Programmazione dinamica · Algoritmi greedy · Divide et impera · BacktrackingAlgoritmi avanzatiAlgoritmi sulle stringhe · Matematica e teoria dei numeri · Manipolazione dei bit · Alberi di segmenti · Union-FindAlgoritmi praticiStrategia per colloqui di programmazione · Cache LRU · Rate limiting · Hashing consistente
Tutta la documentazione di sviluppo
Community
ProgettiScopri sviluppatori e lavoriLog di sviluppoDecisioni e lezioni appresePromptIstruzioni riutilizzabiliProblemi degli strumenti di IAProblemi e alternative di Claude, Codex, GeminiVetrinaRisultati completatiGuida alla communityCome sviluppiamo in modo aperto
Collabora
Trasferimento tecnicoApp native in Rust ed eguiRealizzazione del sito web10 lingue, account, documentazione e downloadRealizzazione di app desktopRust ed egui, senza WebViewPipeline di rilascio e pagamentoFirma, MSI, deb, rpm, AppImage, hashPartner commercialeConsigliaci e ricevi il 30%ContattiSviluppo, partnership e investimenti
Servizi
Desktop remotoRaggiungi il tuo computer dal browserPacchetti di installazione su misuraSolo il necessario, impostazioni precaricate
Acquista
IT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Accedi
Accedi
TASTEDEV

Dai piccoli strumenti a uno sviluppo migliore.

support@tastedev.netSostieni TASTEDEV
ProdottiGamma di prodottiAcquistaDocsDownloadMarketplaceAssistenza
CommunityProgettiLog di sviluppoPromptProblemi degli strumenti di IAVetrina
NormeInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
012345678901234567890123456789012345678901234567890123456789
Ieri
012345678901234567890123456789012345678901234567890123456789
Visualizzazioni totali
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
Società
GXSOFT
Rappresentante
CHOI YOUNG GU
Numero di registrazione
853-44-00368
Indirizzo
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefono
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsabile privacy
CHOI YOUNG GU

© 2026 TASTEDEVLe informazioni sui prodotti si basano su fonti di sviluppo verificate.Rilasciato · in miglioramento

Documentazione di Backtracking
Backtracking
Backtracking ConceptsHow It WorksImplementationComplexityPractice ProblemsBacktracking in the Real World
Discussioni

Guida a Backtracking · 5/6

Practice Problems

Per ora questo capitolo è disponibile solo in inglese.

Backtracking problems look different on the surface, but once you decide what counts as one step and when to prune, most of them fit the same template. Try the four problems below on your own first, then compare your approach with the one given.

Problem 1: balanced parentheses

Given an integer n, list every valid string made of n opening and n closing parentheses. For n = 2 the answer is (()) and ()().

Approach: append one character at a time. An opening parenthesis is allowed only while fewer than n have been used, and a closing one only while fewer have been closed than opened. These two rules are the pruning that prevents invalid strings from ever being built.

def parentheses(n):
    out = []

    def dfs(s, opened, closed):
        if len(s) == 2 * n:
            out.append(s)
            return
        if opened < n:
            dfs(s + "(", opened + 1, closed)
        if closed < opened:
            dfs(s + ")", opened, closed + 1)

    dfs("", 0, 0)
    return out

print(parentheses(3))
# ['((()))', '(()())', '(())()', '()(())', '()()()']

Problem 2: find a word in a grid

You are given a 2D grid of letters and a word. Decide whether the word can be spelled by moving between horizontally or vertically adjacent cells, using each cell at most once.

Approach: start a search from every cell. Mark the current cell as in use by overwriting it with # (choose), look for the next letter in four directions (explore), then restore the original letter (unchoose). Return immediately when a letter does not match.

def exists(grid, word):
    rows, cols = len(grid), len(grid[0])

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

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

board = [list("CAT"), list("OXD"), list("DEN")]
print(exists(board, "CODE"), exists(board, "COAT"))  # True False

Problem 3: permutations with duplicates

List the distinct permutations of a list that contains repeated values, such as [1, 1, 2]. No permutation may appear twice in the output.

Approach: sort first. Picking the same value twice at the same depth repeats an identical branch, so skip a value when the equal value right before it has not been used yet. This shrinks the search itself, which is better than generating duplicates and removing them with a set.

Domande su questo capitolo?
Capitolo precedenteComplexityCapitolo successivoBacktracking in the Real World
def unique_permutations(nums):
    nums = sorted(nums)
    used = [False] * len(nums)
    result, path = [], []

    def dfs():
        if len(path) == len(nums):
            result.append(path[:])
            return
        for i in range(len(nums)):
            if used[i]:
                continue
            if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:
                continue
            used[i] = True
            path.append(nums[i])
            dfs()
            path.pop()
            used[i] = False

    dfs()
    return result

print(unique_permutations([1, 1, 2]))  # [[1, 1, 2], [1, 2, 1], [2, 1, 1]]

Problem 4: solve a Sudoku

Fill in a 9x9 Sudoku board where empty cells are marked with 0. Assume the puzzle has a solution.

Approach: keep a set of used digits for each row, column, and box so each constraint check is O(1). Fill the empty cells in order; when no digit fits, return False so the previous cell tries its next digit. Once a solution is found, pass True upward so nothing gets undone.

def solve_sudoku(board):
    rows = [set() for _ in range(9)]
    cols = [set() for _ in range(9)]
    boxes = [set() for _ in range(9)]
    empty = []
    for r in range(9):
        for c in range(9):
            d = board[r][c]
            if d:
                rows[r].add(d); cols[c].add(d); boxes[r // 3 * 3 + c // 3].add(d)
            else:
                empty.append((r, c))

    def fill(k):
        if k == len(empty):
            return True
        r, c = empty[k]
        b = r // 3 * 3 + c // 3
        for d in range(1, 10):
            if d in rows[r] or d in cols[c] or d in boxes[b]:
                continue
            board[r][c] = d
            rows[r].add(d); cols[c].add(d); boxes[b].add(d)
            if fill(k + 1):
                return True
            rows[r].remove(d); cols[c].remove(d); boxes[b].remove(d)
        board[r][c] = 0
        return False

    return fill(0)

To make it faster, always fill the remaining cell with the fewest candidates next (MRV). On hard puzzles this cuts the number of visited nodes dramatically.

Summary

  • Decide the unit of one step (a character, a cell, an element) and the pruning rule first; the code then follows the usual template.
  • Rather than filtering duplicate solutions afterwards, block identical choices at the same depth so they are never generated.
  • When one solution is enough, return True to end the search early.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.