Why Should You Write Brute Force First? Define the Complete Search Space



☰

Start NorthStar

Python DSA Notes

Why Should You Write Brute Force First? Define the Complete Search Space

Define every candidate, estimate the full search space, build a correct baseline, and only then add pruning or memoization.

Python DSA 笔记

为什么要先写 brute force?先把完整搜索空间说清楚

先定义所有候选、估算完整搜索空间并建立正确基线,再加入剪枝或记忆化。

Share this article

Copy the link, open your phone share sheet, scan the QR code for WeChat, or send by email.




Email

“Brute force” can sound like a lack of technique, but it is often the most important first step in algorithm design. A good brute-force solution does not try things randomly. It defines every candidate, generates each candidate exactly once, and uses the constraints to decide whether the full search is affordable.

The Core Idea

Write brute force first not because it must be the final solution, but because it exposes the candidate space, the success condition, and the complexity baseline.

What Brute Force Means

Complete search has three parts:

  1. define one candidate;
  2. generate every candidate systematically;
  3. test whether each candidate satisfies the problem.

In Chances of Winning, one candidate is a complete assignment of outcomes to all remaining games. If each game has three outcomes and R games remain, there are 3^R candidates.

Step 1: Describe the Search Space

Ask four questions:

Question Why it matters
What decisions form one candidate? Defines the state
How many choices does each decision have? Defines the branching factor
How many decisions are made? Defines the depth
What makes a candidate successful? Defines the terminal check

With b choices at each of d levels, the direct leaf count is often b^d.

Step 2: Compare It with the Constraints

Exponential does not automatically mean impossible. 3^6 is only 729, while 2^60 is beyond direct enumeration. Substitute the actual maximum depth before rejecting a method.

Step 3: Build a Correct Baseline

A direct search often acts as a correctness oracle. It stays close to the statement, is easy to test on tiny cases, and gives an optimized version something trustworthy to compare against. A productive order is:

define candidates -> enumerate all -> verify small cases -> optimize

Loops or Recursion?

Use nested loops when the number and structure of choices are fixed, such as enumerating every pair. Use recursion when the number of decisions varies but each level follows the same pattern.

def search(i):
    if i == len(decisions):
        return check_complete_candidate()

    total = 0
    for choice in choices_for(decisions[i]):
        apply(choice)
        total += search(i + 1)
        undo(choice)
    return total

The shared-state contract is essential: when a call returns, the state must match its value at entry. That is why apply-recurse-undo must be exact.

Optimize Only After the Baseline Works

Three common improvements are pruning impossible partial candidates, memoizing repeated states, and choosing a better representation such as a frequency array or bitmask. Every optimization must preserve all successful candidates and must not merge states with different futures.

Worked Model: Chances of Winning

  • Candidate: one complete assignment of remaining game outcomes.
  • Branches: first team wins, second team wins, or tie.
  • Depth: R <= 6 remaining games.
  • Leaves: 3^R <= 729.
  • Success: the favourite finishes strictly above all three opponents.

Once these five lines are precise, the algorithm is nearly written.

Common Misconceptions

  1. Brute force means random guessing. It does not; coverage and uniqueness require proof.
  2. Every exponential algorithm is too slow. The maximum exponent matters.
  3. Pruning should come first. A correct baseline makes pruning safer to design and test.
  4. Counting leaves is enough. The work performed at each leaf also matters.

Practice Questions

  1. How many binary strings of length n exist?
  2. Why are there O(n^2) subarrays?
  3. Why are there n! permutations of n distinct elements?
  4. Which is smaller, 2^20 or 10!?
  5. Write one sentence defining a candidate in Chances of Winning.

“暴力解法”听起来像没有技巧,但在算法学习中,它常常是最重要的第一步。一个好的 brute force 不是“乱试”,而是:清楚定义所有候选、保证一个不漏、一个不重,再用约束判断这个搜索空间是否真的太大。

一句话结论

先写 brute force,不是因为它一定是最终答案,而是因为它把问题的候选空间、正确性标准和复杂度基线全部说清楚。

brute force 到底是什么?

Brute force 可以翻译为直接枚举或完整搜索。它包含三个动作:

  1. 定义一个候选是什么;
  2. 系统地产生所有候选;
  3. 检查每个候选是否满足条件。

例如 CCC Chances of Winning 中,一个候选不是“一支冠军队”,而是“所有剩余比赛的一整套结果”。每场有三种结果,剩余 R 场就有 3^R 个候选。

第一步:先写出搜索空间

遇到“有多少种”“是否存在一种”“找出最优方案”时,先问四个问题:

问题 作用
一个候选由哪些决定组成? 确定状态表示
每个决定有多少种选择? 确定分支数
一共要做多少次决定? 确定深度
哪些候选算成功? 确定检查条件

如果每层有 b 个选择,一共做 d 次决定,最直接的叶子数通常是:

b^d

这个公式不是为了吓人,而是为了做预算。

第二步:用约束决定能不能跑

复杂度不能脱离输入上限讨论。

搜索空间 大致规模 判断
3^6 729 非常小
2^20 1,048,576 可能可行
10! 3,628,800 视每个候选工作量而定
2^60 超过 10^18 不能直接枚举

“指数算法一定不行”是错误的。指数的底数和深度都重要。CCC Chances of Winning 最多只有 6 场剩余比赛,所以 3^6 完全可行。

第三步:先让基线正确

Brute force 很适合作为 correctness oracle,也就是正确性参照:

  • 它通常和题目定义最接近;
  • 它容易手算小例子;
  • 优化版本可以和它对拍;
  • 如果优化出错,可以判断是剪枝、记忆化还是状态表示的问题。

所以常见的开发顺序是:

定义候选 → 写完整枚举 → 小数据验证 → 再优化

循环枚举还是递归枚举?

固定层数、固定结构:循环

枚举所有 pair:

for i in range(n):
    for j in range(i + 1, n):
        check(i, j)

决定数量可变、每步结构相同:递归

def search(i):
    if i == len(decisions):
        return check_complete_candidate()

    total = 0
    for choice in choices_for(decisions[i]):
        apply(choice)
        total += search(i + 1)
        undo(choice)
    return total

递归不是魔法。它只是把“第 i 个决定后,再处理第 i+1 个决定”写得更自然。

为什么 apply-recurse-undo 很重要?

共享列表或计分数组可以避免每层复制状态,但必须维持一个契约:

> 函数返回时,共享状态必须恢复到调用前的样子。

这就是:

apply → recurse → undo

遗漏 undo 会让兄弟分支互相污染;多 undo 一次则会破坏父状态。

从 brute force 到优化

先有正确基线之后,才考虑三类优化:

1. 剪枝

如果能证明当前部分候选无论怎样完成都不会成功,就提前停止。

2. 记忆化

如果不同路径到达同一个完整状态,就只计算一次未来。

3. 更好的表示

频率数组、bitmask、排序或前缀和可能让候选生成和检查更快。

优化必须保持一个原则:不能删除任何可能成功的候选,也不能把不同未来错误地合并。

一个完整例子:Chances of Winning

  • 候选:剩余比赛的一整套结果;
  • 分支:每场第一队赢、第二队赢、平局,共 3 种;
  • 深度:剩余比赛数 R <= 6;
  • 叶子:3^R <= 729;
  • 成功条件:支持队伍严格高于其他三队。

把这五行写清楚,算法基本就已经出现了。

常见误区

“暴力”就是随便试

不是。好的枚举必须有顺序、有边界,并能证明覆盖完整且没有重复。

看见指数就放弃

先代入最大深度。3^6 和 3^30 完全不是同一件事。

一上来就剪枝

没有正确基线,很难证明剪枝没有删掉答案。

只算叶子,不算每个叶子的工作

总成本还要乘上检查一个候选所需的时间。

练习

  1. 枚举长度为 n 的二进制串,搜索空间多大?
  2. 枚举数组中所有区间,为什么是 O(n^2) 个候选?
  3. 枚举 n 个不同元素的排列,为什么是 n!?
  4. 哪个更小:2^20 还是 10!?
  5. 为 Chances of Winning 写一句“一个候选是什么”。

Questions or feedback?

Have a question about this article or want to suggest an improvement? Send us a private message.

Send Feedback

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈

Back to Python DSA Notes
返回Python DSA 笔记

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top