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) · 6/6

Backtracking in the Real World

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

Backtracking is more than an interview technique. It runs inside tools you use every day: regular expression engines, SAT solvers, constraint programming libraries, and logic programming languages. This chapter covers where it shows up, the pitfalls you meet in production code, and where to read more.

Where backtracking runs

  • Regular expression engines: Python re, Java java.util.regex, JavaScript, and PCRE try each alternative of a pattern (|, *, +) in turn and back up on failure. That is what makes features like backreferences possible, and also why some inputs take exponential time.
  • SAT solvers and DPLL: the DPLL algorithm assigns Boolean variables one at a time and backtracks on a contradiction. It is the foundation of modern CDCL SAT solvers used in hardware verification and package dependency resolution.
  • Constraint programming: solvers such as Google OR-Tools CP-SAT model timetables, shift rosters, and production schedules as variables and constraints, and use constraint propagation to prune branches before exploring them.
  • Logic programming: in Prolog, trying rules from the top and falling back to the next rule on failure is the execution model itself.
  • Puzzles and games: Sudoku, crossword, and exact cover solvers (Knuth's Dancing Links) are classic examples.
  • Parsers: PEG parsers and some recursive descent parsers try grammar alternatives in order and rewind the input position when one fails.

Pitfall 1: catastrophic backtracking in regexes

A pattern like (a+)+$ can split a run of a characters in exponentially many ways, so on input whose ending does not match, the engine tries every split. Applying such a pattern to user-supplied text opens the door to a denial-of-service attack (ReDoS).

import re
import time

pattern = re.compile(r"(a+)+$")
for n in (16, 18, 20, 22):
    text = "a" * n + "!"
    start = time.perf_counter()
    pattern.match(text)
    print(n, f"{time.perf_counter() - start:.3f}s")
# every extra character roughly doubles the time

Fixes include removing the nested repetition (a+$ matches the same strings here), limiting input length, or switching to an engine with linear-time guarantees such as RE2.

Pitfall 2: recursion depth and copying

Python's default recursion limit is around 1000, so searches thousands of levels deep raise RecursionError. You can raise the limit with sys.setrecursionlimit, but that risks overflowing the C stack; for deep searches an explicit stack is safer.

def subsets_iterative(nums):
    result = []
    stack = [(0, [])]                 # (next index, partial solution)
    while stack:
        i, path = stack.pop()
        if i == len(nums):
            result.append(path)
            continue
        stack.append((i + 1, path))               # branch that skips nums[i]
        stack.append((i + 1, path + [nums[i]]))   # branch that takes it
    return result

print(subsets_iterative([1, 2]))  # [[1, 2], [1], [2], []]
Des questions sur ce chapitre ?
Chapitre précédentPractice Problems

An explicit stack copies state instead of undoing it, so it uses more memory. When the depth is modest, the recursive version is simpler and faster.

Pitfall 3: reinventing the standard library

For plain permutations, combinations, or Cartesian products, the standard library is faster and already tested. Write your own backtracking when you need to prune along the way.

from itertools import combinations, permutations, product

print(list(combinations("ABC", 2)))   # [('A', 'B'), ('A', 'C'), ('B', 'C')]
print(len(list(permutations(range(4)))))  # 24
print(list(product([0, 1], repeat=2)))     # [(0, 0), (0, 1), (1, 0), (1, 1)]

Other things to watch

  • A missing or misordered undo leaks state into other branches, and the results go quietly wrong. Always write choose and unchoose as a pair.
  • A pruning rule that is too aggressive cuts off branches that contain real solutions. For small inputs, keep a test that compares against brute force.
  • If input sizes can grow, estimate the worst-case search size up front and add a time or node budget so the service never hangs.
  • Real scheduling problems with complex constraints are usually better handed to a solver such as CP-SAT than implemented by hand.

Summary

  • Backtracking is the core engine of practical tools: regex engines, SAT solvers, constraint programming, and Prolog.
  • Catastrophic backtracking, recursion depth, and forgotten undo steps are the most common production problems.
  • Leave standard enumerations to the library and hard constraint problems to dedicated solvers; implement backtracking yourself where custom pruning pays off.

Further reading

  • Backtracking (Wikipedia)
  • Eight queens puzzle (Wikipedia)
  • Sudoku solving algorithms (Wikipedia)
  • Constraint satisfaction problem (Wikipedia)
  • itertools (Python documentation)
  • Constraint Optimization (Google OR-Tools)
  • Regular expression Denial of Service - ReDoS (OWASP)

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.