Aller au contenu principal
ProduitsOutils de bureauTASTECADConsultation de plansTASTEFILESGestion de fichiersTASTEFTPTransfert de fichiersTASTESSHEspace de travail à distanceTASTEZIPCompression et extractionTASTEWINMGestion de fichiersOutils pour développeursTASTECODEEnvironnement de développement intégré pour RustTASTESTUDIOEnvironnement intégré de développement et de testTASTEETLIntégration de données (ETL)ServeursTASTEREMOTEServeur de bureau à distanceTASTEGEOServeur géospatialTASTEMAILEspace de travail e-mailInvestissementTASTESTOCKApplication de bureau de trading automatique d'actionsCommencerTéléchargementsDocumentationAcheterTous les produits
Marketplace
Actualités
TechActualitésL’actu dev du jourDocs développeursLangages de programmationRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks d'applications et de bureauTauriFlutterReact NativeElectronAlgorithmesBases des algorithmesAlgorithmes essentielsAlgorithmes avancésAlgorithmes pratiques
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrineGuide de la communauté
CollaborerTransfert techniqueRéalisation de site webRéalisation d'application de bureauChaîne de publication et de paiementPartenaire commercialContact
ServicesBureau à distancePaquets d'installation sur mesure
TASTEDEV
Produits

Outils de bureau

TASTECADDes plans complexes, ouverts en toute légèretéTASTEFILESSeulement les fichiers utiles, au plus viteTASTEFTPLe chemin le plus net pour vos fichiersTASTESSHEntre vos serveurs et vous, un lien plus solideTASTEZIPCompresser plus vite, extraire en toute sécuritéTASTEWINMUn gestionnaire de fichiers à deux volets, pensé pour le clavier

Outils pour développeurs

TASTECODEModifier, compiler, déboguer et tester vos apps Rust dans une seule fenêtreTASTESTUDIODe l’édition aux tests à distance et aux corrections IA approuvéesTASTEETLDéplacer les données, les valeurs sous les yeux

Serveurs

TASTEREMOTEUn bureau à distance hébergé sur votre propre serveurTASTEGEOUn serveur géospatial compatible GeoServer, reconstruit en RustTASTEMAILReprenez la maîtrise de vos e-mails

Investissement

TASTESTOCKDu trading automatique d'actions selon vos règles : quand, et quoi

Commencer

TéléchargementsDernières versions de chaque produitDocsUtiliser chaque produitAcheterAbonnements et licences perpétuellesTous les produitsTous les produits en un coup d’œil
Tous les produits
MarketplaceActualités
Tech

Actualités

L’actu dev du jourAnnonces officielles : langages, frameworks, GitHub et IADocs développeursGuides des langages, frameworks et algorithmes

Langages de programmation

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks serveurSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks d'applications et de bureauTauriFlutterReact NativeElectron

Algorithmes

Bases des algorithmesAnalyse de complexité · Tri · Recherche · Structures de données de base · Arbres et tasAlgorithmes essentielsParcours de graphe · Plus courts chemins et arbres couvrants · Programmation dynamique · Algorithmes gloutons · Diviser pour régner · Backtracking (retour sur trace)Algorithmes avancésAlgorithmes sur les chaînes · Mathématiques et théorie des nombres · Manipulation de bits · Arbres de segments · Union-FindAlgorithmes pratiquesStratégie pour les entretiens de codage · Cache LRU · Limitation de débit · Hachage cohérent
Toute la documentation de développement
Communauté
ProjetsDécouvrir les créateurs et leurs travauxJournaux de développementDécisions et enseignementsPromptsInstructions réutilisablesProblèmes d’outils d’IAProblèmes et contournements de Claude, Codex, GeminiVitrineRéalisations terminéesGuide de la communautéConstruire en toute transparence
Collaborer
Transfert techniqueApplications natives en Rust et eguiRéalisation de site web10 langues, comptes, documentation et téléchargementsRéalisation d'application de bureauRust et egui, sans WebViewChaîne de publication et de paiementSignature, MSI, deb, rpm, AppImage, empreintesPartenaire commercialRecommandez-nous, touchez 30 %ContactDéveloppement, partenariats, investissement
Services
Bureau à distanceAccédez à votre ordinateur depuis le navigateurPaquets d'installation sur mesureSeulement l'utile, réglages préchargés
Acheter
FR
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Se connecter
Se connecter
TASTEDEV

Des petits outils à un meilleur développement.

support@tastedev.netSoutenir TASTEDEV
ProduitsGamme de produitsAcheterDocsTéléchargementsMarketplaceAssistance
CommunautéProjetsJournaux de développementPromptsProblèmes d’outils d’IAVitrine
RèglesÀ proposPolitique de confidentialitéConditions d'utilisationConditions d’abonnementRemboursementRègles de la communauté
CompteSe connecterS'inscrire
Visiteurs
Aujourd’hui
Hier
Vues au total
Société
GXSOFT
Représentant
CHOI YOUNG GU
Numéro d’enregistrement
853-44-00368
Adresse
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Téléphone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsable de la confidentialité
CHOI YOUNG GU

© 2026 TASTEDEVLes informations produit s'appuient sur des sources de développement vérifiées.Publié · en amélioration

Documentation Backtracking (retour sur trace)
Backtracking (retour sur trace)
Backtracking ConceptsHow It WorksImplementationComplexityPractice ProblemsBacktracking in the Real World
Discussions

Guide Backtracking (retour sur trace) · 1/6

Backtracking Concepts

Ce chapitre n'est disponible qu'en anglais pour le moment.

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.

Des questions sur ce chapitre ?
Chapitre suivantHow 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 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.