Vai al contenuto principale
ProdottiStrumenti desktopTASTECADVisualizzazione disegniTASTEFILESGestione fileTASTEFTPTrasferimento fileTASTESSHSpazio di lavoro remotoTASTEZIPCompressione ed estrazioneTASTEWINMGestione fileStrumenti per sviluppatoriTASTECODEAmbiente di sviluppo integrato per RustTASTESTUDIOAmbiente integrato di sviluppo e testTASTEETLIntegrazione dati (ETL)ServerTASTEREMOTEServer di desktop remotoTASTEGEOServer geospazialeTASTEMAILSpazio di lavoro emailInvestimentiTASTESTOCKApp desktop di trading automatico azionarioIniziaDownloadDocumentazioneAcquistaTutti 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ù sicuroTASTEWINMUn file manager a due pannelli pensato per la tastiera

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

Investimenti

TASTESTOCKTrading automatico azionario secondo le regole che decidi tu: quando e che cosa

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
NormeChi siamoInformativa sulla privacyTermini di servizioCondizioni di abbonamentoRimborsiLinee guida della community
AccountAccediRegistrati
Visitatori
Oggi
Ieri
Visualizzazioni totali
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 · 1/6

Backtracking Concepts

Per ora questo capitolo è disponibile solo in inglese.

Backtracking is a search technique that builds an answer one piece at a time and, as soon as the choices made so far break a rule, steps back to the previous decision and tries something else. Unlike brute force, which generates every complete candidate and only then checks it, backtracking abandons hopeless paths halfway, so it often solves the same problem with a tiny fraction of the work. This chapter introduces the vocabulary, the basic template, and the situations where backtracking is the right tool.

The state-space tree

The easiest way to picture what backtracking explores is a state-space tree. The root is the empty state where nothing has been chosen yet, and each step down the tree adds one more choice. A leaf holds one complete candidate. Here is the tree that generates the permutations of [1, 2, 3]:

                 []
       /         |         \
     [1]        [2]        [3]
    /   \      /   \      /   \
 [1,2] [1,3] [2,1] [2,3] [3,1] [3,2]
   |     |     |     |     |     |
[1,2,3] ...                    [3,2,1]

Backtracking walks this tree depth first, but whenever it can tell that a node cannot lead to a valid solution, it skips the entire subtree below that node. This is called pruning.

Vocabulary

  • Partial solution: the list of choices made so far, usually carried around as a list such as path.
  • Candidates: the values that may be chosen next from the current state.
  • Promising: a node is promising if extending it could still reach a solution.
  • Pruning: stopping at a node that is not promising and returning to its parent.
  • Constraint: a rule every solution must satisfy, such as "no two queens share a column" or "the sum must not exceed the target".

Choose, explore, unchoose

Almost every backtracking routine repeats the same three moves. Choose a candidate and add it to the partial solution, explore recursively from that state, and when the call returns, unchoose by removing what you added. The undo step is what lets every branch share a single path list.

def backtrack(path, choices, result):
    if is_solution(path):
        result.append(path[:])      # store a copy
        return
    for c in candidates(path, choices):
        if not is_valid(path, c):   # prune
            continue
        path.append(c)              # choose
        backtrack(path, choices, result)  # explore
        path.pop()                  # unchoose

If you write result.append(path) without the copy, every stored entry refers to the same list, which is empty by the time the search finishes. It is one of the most common backtracking bugs.

Domande su questo capitolo?
Capitolo successivoHow It Works

A small example: subsets

Splitting on "take this element or leave it" produces the subset tree. With n elements there are 2^n leaves.

def subsets(nums):
    result, path = [], []

    def dfs(i):
        if i == len(nums):
            result.append(path[:])
            return
        path.append(nums[i])   # branch that takes nums[i]
        dfs(i + 1)
        path.pop()
        dfs(i + 1)             # branch that skips it

    dfs(0)
    return result

print(subsets([1, 2, 3]))
# [[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]

An example with pruning

Generate all binary strings of length n with no two adjacent 1s. Refusing to append a 1 right after another 1 is the pruning rule, and it explores far fewer nodes than building every string and filtering afterwards.

def no_adjacent_ones(n):
    out = []

    def dfs(s):
        if len(s) == n:
            out.append(s)
            return
        dfs(s + "0")
        if not s.endswith("1"):   # never try 1 after 1
            dfs(s + "1")

    dfs("")
    return out

print(no_adjacent_ones(3))  # ['000', '001', '010', '100', '101']

When to reach for backtracking

  • You need to enumerate every solution that satisfies some condition: permutations, combinations, subsets, lists of paths.
  • You are solving a constraint satisfaction problem (CSP): N-Queens, Sudoku, graph coloring, scheduling.
  • The input is small enough (roughly n up to about 20) that exponential time is still acceptable.
  • Subproblems do not overlap, so dynamic programming (DP) has nothing to reuse.

On the other hand, if you only need a count and the same subproblems repeat, DP is usually better, and if the locally best choice always leads to the global optimum, a greedy algorithm wins. The complexity chapter compares these in detail.

Summary

  • Backtracking is a depth-first search over a state-space tree that cuts off branches that cannot succeed.
  • The code is a loop of choose, explore, unchoose, and solutions are stored as copies of the partial solution.
  • How early and how aggressively you prune decides how fast the search runs.

0 commenti

Commenti principaliPrima i più recenti

Accedi · Accedi per lasciare un commento.