跳到正文
产品桌面工具TASTECAD图纸查看TASTEFILES文件管理TASTEFTP文件传输TASTESSH远程工作空间TASTEZIP压缩与解压开发工具TASTECODERust 集成开发环境TASTESTUDIO集成开发与测试环境TASTEETL数据整合(ETL)服务器TASTEREMOTE远程桌面服务器TASTEGEO空间信息服务器TASTEMAIL邮件工作空间开始使用下载文档购买全部产品
市场
资讯
技术资讯今日开发资讯开发文档编程语言RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartWeb 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express应用与桌面框架TauriFlutterReact NativeElectron算法算法基础核心算法进阶算法实用算法
社区项目开发日志提示词AI 工具问题作品展示社区指南
合作技术传授网站构建桌面应用构建发布与支付流水线销售合作伙伴联系我们
服务远程桌面安装包定制
TASTEDEV
产品

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳

开发工具

TASTECODE在一个窗口中完成 Rust 应用的编辑、构建、调试和测试TASTESTUDIO从编辑到远程测试,再到经批准的 AI 修复TASTEETL边看数值,边搬数据

服务器

TASTEREMOTE在自己的服务器上运行的远程桌面TASTEGEO用 Rust 重新构建兼容 GeoServer 的空间信息服务器TASTEMAIL把邮件的主导权拿回自己手中

开始使用

下载所有产品的最新版本文档各产品使用方法购买订阅与永久许可全部产品一览全部产品
全部产品
市场资讯
技术

资讯

今日开发资讯语言、框架、GitHub 与 AI 官方发布开发文档语言、框架与算法指南

编程语言

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

框架

Web 前端框架Next.jsReactVue.js · NuxtSvelteKitAngular
服务端框架Spring BootDjangoFastAPIASP.NET CoreNestJS · Express
应用与桌面框架TauriFlutterReact NativeElectron

算法

算法基础复杂度分析 · 排序 · 查找 · 基础数据结构 · 树与堆核心算法图遍历 · 最短路径与最小生成树 · 动态规划 · 贪心算法 · 分治法 · 回溯法进阶算法字符串算法 · 数学与数论 · 位运算 · 线段树 · 并查集实用算法编程面试解题策略 · LRU 缓存 · 限流 · 一致性哈希
查看全部开发文档
社区
项目发现开发者与作品开发日志决策与试错提示词可复用的指令AI 工具问题Claude、Codex、Gemini 的问题与变通办法作品展示已完成的成果社区指南我们如何公开构建
合作
技术传授用 Rust 和 egui 打造原生应用网站构建10 种语言、账户、文档与下载桌面应用构建Rust 和 egui,不用 WebView发布与支付流水线签名、MSI、deb、rpm、AppImage、哈希销售合作伙伴推荐即得 30%联系我们开发、合作与投资咨询
服务
远程桌面用浏览器连接你的电脑安装包定制只装需要的,设置预先放好
购买
ZH
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
登录
登录
TASTEDEV

从小工具到更好的开发。

support@tastedev.net支持 TASTEDEV
产品产品线购买文档下载市场客户支持
社区项目开发日志提示词AI 工具问题作品展示
政策隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
012345678901234567890123456789012345678901234567890123456789
昨天
012345678901234567890123456789012345678901234567890123456789
累计浏览
0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789
公司名称
GXSOFT
法定代表人
CHOI YOUNG GU
营业执照号
853-44-00368
地址
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
电话
+82-10-4404-1523
电子邮件
whitecalvin@tastedev.net
个人信息保护负责人
CHOI YOUNG GU

© 2026 TASTEDEV产品信息以已验证的开发源码为准。已发布·持续改进

动态规划 文档
动态规划
ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
讨论

动态规划 指南 · 4/6

Complexity

本章目前仅提供英文版。

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.

对本章有疑问?
上一章Implementation下一章Practice 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 条评论

热门评论最新优先

登录 · 登录后即可发表评论。