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

桌面工具

TASTECAD复杂图纸,轻松打开TASTEFILES只要需要的文件,最快送达TASTEFTP让文件往来,干净利落TASTESSH你与服务器之间,连接更牢靠TASTEZIP压得更快,解得更稳TASTEWINM以键盘为主、用两个窗格整理文件的文件管理器

开发工具

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

服务器

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

投资

TASTESTOCK何时、做什么——按你定下的规则运行的股票自动交易

开始使用

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

资讯

今日开发资讯语言、框架、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 工具问题作品展示
政策关于我们隐私政策服务条款订阅条款退款政策社区规范
账户登录注册
访客
今天
昨天
累计浏览
公司名称
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产品信息以已验证的开发源码为准。已发布·持续改进

贪心算法 文档
贪心算法
Greedy ConceptsHow It WorksImplementationComplexityPractice ProblemsReal-World Use
讨论

贪心算法 指南 · 1/6

Greedy Concepts

本章目前仅提供英文版。

A greedy algorithm builds a solution through a sequence of choices, and at each step it takes whatever looks best right now, never revisiting that decision. Unlike exhaustive search, which tries every option, or dynamic programming, which tabulates answers to subproblems, a greedy algorithm follows a single path. That makes it short and fast, but you have to prove separately that the path actually leads to an optimal answer.

Vocabulary

TermMeaning
Greedy choicePicking the candidate that is best by a fixed rule in the current state
Greedy choice propertySome optimal solution always contains the first greedy choice
Optimal substructureAfter the first choice, an optimal answer to the remaining problem completes an optimal answer overall
Exchange argumentA proof that swaps parts of an optimal solution toward the greedy one without making it worse
Greedy stays aheadA proof that after every step the greedy solution is at least as good as any other

A greedy algorithm is correct when the greedy choice property and optimal substructure both hold. The first guarantees that the first choice is never a mistake; the second guarantees that the rest of the problem can be solved the same way. Together they give an inductive proof that every choice is safe.

How an exchange argument goes

The exchange argument is the workhorse of greedy proofs, and it almost always has the same shape.

  1. Take an arbitrary optimal solution OPT.
  2. Find the first place where OPT differs from the greedy solution.
  3. Show that replacing OPT's element there with the greedy element keeps the solution valid and no worse.
  4. Repeating the swap turns OPT into the greedy solution, so the greedy solution is optimal too.

Take the problem of choosing as many non-overlapping meetings as possible, where greedy picks the meeting that finishes first. Replace the first meeting of any optimal schedule with the earliest-finishing one: the new meeting ends no later than the old one, so it cannot collide with anything that followed. The count is unchanged, so the swap costs nothing.

When greedy works: making change

Paying out change with the largest coins first is the most familiar greedy algorithm. In a well-designed coin system such as US coins (1, 5, 10, 25 cents) it always uses the fewest coins.

def greedy_coins(coins, amount):
    """Use as many large coins as possible. None if the amount cannot be made."""
    count = 0
    for coin in sorted(coins, reverse=True):
        take, amount = divmod(amount, coin)
        count += take
    return count if amount == 0 else None


print(greedy_coins([1, 5, 10, 25], 63))  # 6 (25 * 2 + 10 + 1 * 3)

When greedy fails: a counterexample

Now suppose the coins are 1, 3 and 4 and you owe 6. Greedy grabs a 4 and then two 1s, three coins in total. Two 3s would do with only two coins. The first greedy choice (the 4) is not part of any optimal answer, so the greedy choice property is broken. Here you need dynamic programming, which computes the minimum for every amount.

def min_coins(coins, amount):
    """Dynamic programming: best[a] = fewest coins that make a."""
    INF = float("inf")
    best = [0] + [INF] * amount
    for a in range(1, amount + 1):
        for c in coins:
            if c <= a and best[a - c] + 1 < best[a]:
                best[a] = best[a - c] + 1
    return best[amount] if best[amount] != INF else None


print(greedy_coins([1, 3, 4], 6), min_coins([1, 3, 4], 6))  # 3 2

When the proof is hard: compare on small inputs

Before you write a proof, or whenever you doubt one, the quickest check is to compare the greedy answer with a known-correct one (brute force or dynamic programming) on small inputs. A single counterexample is enough to reject a greedy rule.

def find_counterexample(coins, limit=100):
    for amount in range(1, limit + 1):
        g, d = greedy_coins(coins, amount), min_coins(coins, amount)
        if g != d:
            return amount, g, d
    return None


print(find_counterexample([1, 3, 4]))       # (6, 3, 2)
print(find_counterexample([1, 5, 10, 25]))  # None

Finding no counterexample is not a proof, but it is very effective at discarding wrong rules early.

When to think greedy

  • Processing items in sorted order, or in the order a priority queue hands them out, seems natural
  • The question asks for a maximum count, a minimum cost or a minimum number, and choices do not interact much
  • The data can be ranked by a single key such as an interval end, a deadline or a weight
  • A dynamic programming state would be too large and you need a simpler rule

Summary

  • A greedy algorithm takes the best-looking option at every step and never backtracks.
  • It is correct when the greedy choice property and optimal substructure hold, usually shown with an exchange argument.
  • One counterexample, such as coins 1, 3, 4 and amount 6, is enough to rule a greedy rule out; use dynamic programming instead.
  • Comparing against brute force on small inputs filters out wrong rules before you invest in a proof.
对本章有疑问?
下一章How It Works

0 条评论

热门评论最新优先

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