Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoEmpezarDescargasDocumentació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 seguro

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

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íticasPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
012345678901234567890123456789012345678901234567890123456789
Ayer
012345678901234567890123456789012345678901234567890123456789
Vistas totales
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
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 Programación dinámica
Programación dinámica
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
Debates

Guía de Programación dinámica · 4/6

Complexity

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

Analyzing a DP is usually mechanical: count the states, count the work per state, and multiply. This chapter applies that rule to the classic problems, explains why knapsack is called pseudo-polynomial, compares memoization with tabulation, and shows how to cut memory with rolling arrays.

The basic rule

  • Time = number of states x work per transition.
  • Space = number of states kept in memory at the same time.

For Fibonacci there are n + 1 states and each does constant work, so time is O(n). For LCS there are (n + 1)(m + 1) states, each doing constant work, so time is O(nm). For coin change with k coin types, each of the amount + 1 states looks at k coins, giving O(amount x k).

Classic problems at a glance

ProblemStateTimeSpace (table)Space (optimized)
FibonaccinO(n)O(n)O(1)
Coin change (min coins)amountO(A x k)O(A)O(A)
0/1 knapsackitem, capacityO(n x W)O(n x W)O(W)
LCS / edit distancei, jO(n x m)O(n x m)O(min(n, m))
LIS, simple DPend indexO(n^2)O(n)O(n)
LIS, patience sortinglengthO(n log n)O(n)O(n)

There is rarely a separate best or worst case for a DP: the table is filled completely regardless of the input values. Memoization can be faster in practice when only a fraction of the states is reachable from the starting state.

Pseudo-polynomial time

O(n x W) for knapsack looks polynomial, but W is a number, not the length of the input. Writing W takes only about log2(W) bits, so adding one more bit to the input can double the running time. Such algorithms are called pseudo-polynomial. The 0/1 knapsack problem is NP-hard in general; DP is practical only when capacities are reasonably small integers. When is huge but is tiny (say 40 items), meet-in-the-middle enumeration is often a better choice.

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorImplementationCapítulo siguientePractice Problems
W
n

Memoization vs tabulation

AspectMemoization (top-down)Tabulation (bottom-up)
Code shapeRecursive function plus cacheLoops over a table
States computedOnly reachable onesAll of them
OrderFound automaticallyYou must choose it
OverheadFunction calls, hashing of argumentsArray indexing
Recursion depthCan hit limits (Python default about 1000)No recursion
Space optimizationHardNatural (rolling rows)

In Python the recursion limit is the most common surprise. A memoized function on a chain of a few thousand states raises RecursionError, and sys.setrecursionlimit does not always help: recent Python versions also limit how deep calls may nest through C code, and the functools.cache wrapper is written in C. A simple workaround is to warm the cache from small to large, so every call finds its smaller states already stored.

from functools import cache


@cache
def ways(n: int) -> int:
    """Number of ways to climb n stairs with steps of 1 or 2."""
    if n <= 1:
        return 1
    return ways(n - 1) + ways(n - 2)


try:
    ways(5_000)
except RecursionError:
    print("too deep")

for i in range(5_001):  # warm up: each call recurses only one level
    ways(i)
print(ways(5_000) % 1_000_000_007)
print(ways.cache_info().currsize)  # 5001 states stored

Warming up is really bottom-up evaluation in disguise. For tens of thousands of states, write the loop directly.

Rolling arrays

If a row of the table depends only on the previous row, you never need more than two rows at once. LCS length in O(min(n, m)) space:

def lcs_length(a: str, b: str) -> int:
    if len(b) > len(a):
        a, b = b, a  # make b the shorter string
    prev = [0] * (len(b) + 1)
    for ch in a:
        cur = [0] * (len(b) + 1)
        for j, bj in enumerate(b, start=1):
            cur[j] = prev[j - 1] + 1 if ch == bj else max(prev[j], cur[j - 1])
        prev = cur
    return prev[-1]


print(lcs_length("ABCBDAB", "BDCABA"))  # 4

The trade-off: with only two rows left, you can no longer walk the table backwards to reconstruct the subsequence. Hirschberg's algorithm recovers it in linear space with a divide-and-conquer trick, at roughly twice the time.

Beating the obvious recurrence

Sometimes a better state definition changes the complexity class. The simple LIS recurrence checks every earlier index, giving O(n^2). Keeping, for each length, the smallest possible tail value lets binary search replace the inner loop:

from bisect import bisect_left


def lis_length(nums: list[int]) -> int:
    tails: list[int] = []  # tails[k] = smallest tail of an increasing run of length k + 1
    for x in nums:
        k = bisect_left(tails, x)
        if k == len(tails):
            tails.append(x)
        else:
            tails[k] = x
    return len(tails)


print(lis_length([3, 1, 4, 1, 5, 9, 2, 6]))  # 4, for example 1, 4, 5, 9

tails stays sorted, so each element costs O(log n) and the total is O(n log n).

Comparison with other approaches

ApproachTypical cost on knapsack-like problemsCorrect?
Brute force over all subsetsO(2^n)Yes, but only for small n
Greedy by value/weight ratioO(n log n)Not for 0/1 knapsack (correct for the fractional version)
Dynamic programmingO(n x W)Yes, when W is small
Branch and boundExponential worst case, often fastYes

Summary

  • Time is states x transition cost; space is the states you keep at once.
  • Knapsack DP is pseudo-polynomial because it depends on the numeric value of W.
  • Memoization computes only reachable states but pays for recursion; tabulation is predictable and easy to optimize.
  • Rolling arrays cut memory to one or two rows at the cost of reconstruction.

0 comentarios

Comentarios destacadosMás recientes primero

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