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

Complexity

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

The running time of backtracking boils down to nodes visited times work per node. In the worst case it walks the whole state-space tree, so most problems are exponential or factorial. Pruning cannot change that upper bound, but it can drastically shrink the number of nodes actually visited. This chapter lists the complexity of the classic problems, measures the effect of pruning, and compares backtracking with brute force and dynamic programming (DP).

Complexity of the classic problems

ProblemNodes (or solutions)TimeExtra space
Subsets2^nO(n · 2^n)O(n)
Permutationsabout e · n!O(n · n!)O(n)
Combinations C(n, k)C(n, k) solutionsO(k · C(n, k))O(k)
N-Queensat most n!at most O(n!)O(n)
Sudoku with m blanksat most 9^mat most O(9^m)O(m)

The extra factor n or k in the time column is the cost of copying each solution into the output. The space column counts only the recursion depth and path; the output list needs room for every solution on top of that. The best case depends on the problem. A Sudoku solver that needs a single answer can finish in time proportional to the number of blanks if its first guesses are right, but when every solution must be listed, the number of solutions itself is a lower bound.

Measuring the effect of pruning

Count the nodes the N-Queens search actually visits, and compare with placing a queen in any column of each row (n^n) and with only avoiding repeated columns (n!).

def count_nodes(n):
    cols, diag, anti = set(), set(), set()
    visited = 0

    def place(row):
        nonlocal visited
        visited += 1
        if row == n:
            return
        for c in range(n):
            if c in cols or row - c in diag or row + c in anti:
                continue
            cols.add(c); diag.add(row - c); anti.add(row + c)
            place(row + 1)
            cols.remove(c); diag.remove(row - c); anti.remove(row + c)

    place(0)
    return visited

for n in (4, 8, 12):
    print(n, count_nodes(n))
Des questions sur ce chapitre ?
Chapitre précédentImplementationChapitre suivantPractice Problems
nSolutionsNodes visitedn!n^n
421724256
8922,05740,32016,777,216
1072435,5393,628,80010,000,000,000
1214,200856,189479,001,600about 8.9 trillion

At n = 12 the search visits roughly 0.2% of n! nodes. The bound is the same, but the real amount of work differs by orders of magnitude, and that is what makes backtracking practical.

Cutting deeper with sorting and bounds

When looking for subsets that sum to target, sorting the numbers first means that once a number exceeds the remaining sum, every number after it can be skipped too. The key detail is that you can break instead of continue.

def subset_sum(nums, target):
    nums = sorted(nums)
    result, path = [], []

    def dfs(start, remain):
        if remain == 0:
            result.append(path[:])
            return
        for i in range(start, len(nums)):
            if nums[i] > remain:
                break                 # later numbers are larger: cut them all
            path.append(nums[i])
            dfs(i + 1, remain - nums[i])
            path.pop()

    dfs(0, target)
    return result

print(subset_sum([8, 2, 6, 3, 5], 11))  # [[2, 3, 6], [3, 8], [5, 6]]

Brute force and DP compared

TechniqueHow it searchesGood fitWeakness
Brute forcebuild every candidate, then checktiny inputs, test oraclesbuilds invalid candidates in full
Backtrackingcheck while building, undo on failurelisting solutions, constraint problemsworst case still exponential
Branch and boundbacktracking plus cut-offs from a bound on the best valueoptimization (knapsack, TSP)needs a good bounding function
DPstore answers to overlapping subproblemscounting, minimum or maximumhard to list every solution

The right tool depends on the question. To list every subset that sums to target, use backtracking. To ask whether one exists or how many there are, DP answers in O(n · target) and is far faster.

def count_subset_sum(nums, target):
    ways = [1] + [0] * target       # ways[s] = number of subsets summing to s
    for x in nums:
        for s in range(target, x - 1, -1):
            ways[s] += ways[s - x]
    return ways[target]

print(count_subset_sum([8, 2, 6, 3, 5], 11))  # 3

Summary

  • The upper bound of backtracking is the size of the state-space tree, typically on the order of 2^n or n!.
  • Pruning does not change that bound, but it cuts the nodes actually visited by orders of magnitude.
  • Use backtracking when every solution must be listed; consider DP first when you only need a count or an optimum and subproblems overlap.

0 commentaire

Meilleurs commentairesPlus récents d'abord

Se connecter · Connectez-vous pour laisser un commentaire.