Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Backtracking (vuelta atrás)
Backtracking (vuelta atrás)
Backtracking ConceptsHow It WorksImplementationComplexityPractice ProblemsBacktracking in the Real World
Debates

Guía de Backtracking (vuelta atrás) · 1/6

Backtracking Concepts

Por ahora, este capítulo solo está disponible en inglés.

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.

¿Tienes preguntas sobre este capítulo?
Capítulo siguienteHow 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 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.