再帰
導入済み
15:34
探索 & ソート
百万人の名前が入った電話帳があります。一つずつ確認していくと、百万回の比較が必要になるかもしれません。しかし、すでにそのコツはご存知でしょう:…で開いてみてください。
英語のナレーション・英語と中国語の字幕を切り替え可能
このレッスンの内容
| English | 意味 |
|---|---|
| recursive/rɪˈkɜːsɪv/ | 再帰的 |
| loop/luːp/ | A structure that repeats a sequence of instructions. |
| base case/beɪs keɪs/ | 基底ケース |
| recursive case/rɪˈkɜːsɪv keɪs/ | 再帰ケース |
| recursive call/rɪˈkɜːsɪv kɔːl/ | A function call made by the same function while it is running. |
| trace/treɪs/ | To follow an algorithm step by step and record its values. |
| call stack/kɔːl stæk/ | 呼び出しスタック |
| recursion/rɪˈkɜːʃn/ | The use of a rule inside its own definition to express repetition. |
| function/ˈfʌŋkʃn/ | A mapping that assigns exactly one output to each allowed input. |
| Winding up | The stage when recursive calls are made until a base case is reached. |
| Unwinding | The stage when recursive calls return their results to the calls waiting for them. |
| stack/stæk/ | A last-in, first-out data structure in which items are added and removed at the same end. |
| parameters/pəˈræmɪtəz/ | Values that specify a model or function, or named inputs that a subroutine receives. |
| local variables/ˈləʊkl ˈveərɪəblz/ | A variable whose name is accessible only within a particular function, block or other limited scope. |
| stack frame/stæk freɪm/ | スタックフレーム |
| return address/rɪˈtɜːn əˈdres/ | The location where execution should resume after a called routine finishes, saved as part of managing the call. |
| pushed | Added to the top of the call stack when a function is called. |
| popped | Removed from the top of the call stack when a function returns. |
| ADT | A description of data and its allowed operations, separate from how it is stored. |
| memory/ˈmeməri/ | The part of a computer that holds data and programs currently in use. |
| stack overflow/stæk ˌəʊvəˈfləʊ/ | スタックオーバーフロー |
| Deep recursion | Even a correct recursion of a million levels needs a million frames, so it can exhaust memory where a loop would use none. |
| Fibonacci | A sequence starting with zero and one, where each later number is the sum of the previous two. |
| memoisation/ˌmeməʊaɪˈzeɪʃn/ | メモ化 |
| iteration/ˌɪtəˈreɪʃn/ | Repeating a sequence of instructions or calculations. |
| self-similar | Describes a problem that contains a smaller version of itself. |
| tree traversal | The process of visiting each node in a tree in a particular order. |
| divide and conquer/dɪˈvaɪd ænd ˈkɒŋkə/ | A method that divides a problem into smaller problems and combines their solutions. |
| binary search/ˈbaɪnəri sɜːtʃ/ | A search of ordered data that repeatedly compares with the middle item and discards half of the remaining search range. |
| merge sort/mɜːdʒ sɔːt/ | A sorting algorithm that divides data into smaller parts, sorts them, and joins them in order. |
| arithmetic overflow | A result that is too large or small for the available number of bits. |
| infinite recursion | When a function keeps calling itself because it never reaches a stopping point. |
自身を含み込む定義
- 先祖とは何かをどう説明するか?あなたの親は先祖である。また、親の先祖もまた先祖である。この2つの文は無限連鎖を定義しており、2つ目の文ではその定義に使われている言葉自体を使っています。
- これは循環論法ではありません。最初の文が連鎖の終端となる場所を与えているからです。これがなければ、定義は永遠に展開されてしまいます。
- プログラムは同じように書けるため、このような連鎖形状の問題に対して、ループよりも再帰的な解法の方が劇的に短くなります。
- このレッスンは基本ケースと再帰的ケース、再帰呼び出しのトレース方法、そして下層で何が起こっているかというコールスタックについてです。

このカードは修正されたため、翻訳が更新されるまで英語で表示されます。
The two cases
FUNCTION Factorial(n : INTEGER) RETURNS INTEGER
IF n = 0 OR n = 1 THEN
RETURN 1 // base case
ELSE
RETURN n * Factorial(n - 1) // recursive case
ENDIF
ENDFUNCTION
- The base case is a version of the problem small enough to answer directly, with no further call. It is what stops the recursion 递归.
- The recursive case calls the function 函数 again with a smaller input, moving towards the base case.
- Both are required. A terminating recursion needs a base case and recursive calls that make progress towards it.

Every recursive algorithm must have a base case because:
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
The base case is the condition that ends the chain of calls; without it the recursion runs forever.
Recursion is a natural fit for self-similar problems (trees, divide-and-conquer), but each call adds a stack frame — so without a base case it overflows the stack.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
A simple counting loop is cleaner for plain iteration; recursion shines when the problem contains smaller copies of itself.
What must a recursive routine have to terminate? Select すべて that apply.
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
A base case alone is not enough: if the input never shrinks, the base case is never reached and frames pile up until the stack overflows.
実演例:再帰のトレース
- トレース
Factorial(4). - Winding up:
Factorial(4)needs4 * Factorial(3), which needs3 * Factorial(2), which needs2 * Factorial(1). Nothing has been multiplied yet; each call is waiting. - 基本ケース:
Factorial(1)は何も呼び出さずに1を返します。 - 巻き下げ:
2 * 1 = 2が返され、次に3 * 2 = 6、そして4 * 6 = 24が返されます。 - 両方の方向を示してください。下方向だけあるいは戻り方向だけのトレースでは、点数の半分を失います。
Recursion unwinds from the leaves up
Step through fib(4) in the order the calls actually finish: the leaves (base cases) resolve first, then each parent combines its children. Notice fib(2) is computed twice — that repeated work is why naive recursion is slow.
What does Factorial(4) return?
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
4 × 3 × 2 × 1 = 24.
マシンが何をしているか
- 各呼び出しには独自のパラメータとローカル変数のコピーが必要です。なぜなら、
Factorial(3)とFactorial(2)は異なるnの値を持つ別の呼び出しだからです。 - これらのコピーはコールスタック上のスタックフレームに格納されます:進行中の呼び出しごとに1つのフレームがあり、パラメータ、ローカル変数、リターンアドレスを保持します。
- 各呼び出し時にフレームはpushされ、リターン時にはpopされます。そのため、呼び出された順序の逆順で値が戻ってきます。コールスタックはまさにADTとしてのスタック(トピック10)です。
Put the events of evaluating Factorial(4) in order.
難易度 3/5 · 200 コイン + 今日初回達成時の小ボーナス
Nothing is multiplied on the way down; every call waits. The multiplications all happen as the stack unwinds.
何が間違っているか
- 基本ケースがない、または到達不可能な基本ケース: 再帰は停止せず、フレームが積み重なってコールスタックのメモリが枯渇します。これをスタックオーバーフローといいます。
- 深い再帰: 正しい百万レベルの再帰でも百万個のフレームが必要となり、ループでは使わないメモリを消費してしまいます。
- 重複作業: 素朴な再帰的フィボナッチは同じ値を指数関数的に多数回計算し直します。ループにするか、メモ化によって初回計算時の結果を保存することで解決できます。

Match each recursion term to what it means.
難易度 2/5 · 140 コイン + 今日初回達成時の小ボーナス
A recursion needs a base case to stop and a recursive case to shrink the problem; each call adds a stack frame.
A stack frame for a function call holds:
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Each frame stores that call's parameters, locals and where to resume — so calls don't trample each other.
Each call in progress keeps its parameters and locals in its own ____ on the call stack.
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Pushed on call, popped on return. That is why values come back in the reverse of the order the calls were made.
再帰か反復か
- 再帰は自己相似性のある問題に適しています。問題自体がより小さなコピーを含んでいる場合です:ツリー走査、二分探索やマージソートのような分割征服、および上記の先祖連鎖など。
- 反復はそれ以外のすべてに適しており、繰り返しのために追加メモリを使用しません。
- 再帰的なものはすべて反復的に記述でき、その逆も真です。選択は、哪一种が問題を明確に表現できるかを、スタックのコストとなるメモリ量と引き合わせることで行います。

A recursive routine crashes with a stack overflow. Which explanation is correct?
難易度 1/5 · 100 コイン + 今日初回達成時の小ボーナス
Stack overflow is about frames, not arithmetic. A number too large for its register is an arithmetic overflow, a different thing entirely.
実演例:リスクを述べる
- ある学生が再帰ルーチンを書き、スタックオーバーフローでクラッシュしました。考えられる原因を2つ挙げよ。
- 基本ケースがなく、または入力が呼び出しごとに小さくならないため基本ケースに到達できず、呼び出しが永遠に続きフレームが蓄積している。
- 再帰は正しいが深すぎる: 非常に多くの呼び出しそれぞれが独自のスタックフレームを保持しており、基本ケースに到達する前にコールスタックのメモリが枯渇している。
- 両方ともフレームの蓄積に関するもの。何が集まり、なぜそれが停止しないかを述べよ。
見落としやすいポイント
- 再帰には基本ケースと入力が小さくなることの両方が必要です。基本ケースだけを名指すことは条件の半分しか満たしていません。
- トレースでは、呼び出しが巻き上がる様子と値が巻き下がる様子を両方示す。どちらの方向にも点数が付く。
- 各呼び出しには独自のパラメータとローカル変数があり、独自のスタックフレームに格納される。これが再帰が反復にはないメモリコストを生む理由である。
- スタックオーバーフローとは、算术的な overflow ではなく、フレームが多すぎてスタックメモリが枯渇することである。
理解できましたか
- 再帰ルーチンには、直接解かれる基本ケースと、より小さい入力で自身を呼び出す再帰的ケースが必要である。
- 両方の方向でトレースする:基本ケースまで呼び出しが巻き上がり、その後値が巻き下がる。
- 各呼び出しにはコールスタック上の独自のスタックフレームがあり、呼び出し時にpushされ、リターン時にpopされる。これが再帰がメモリコストを生む理由である。
- リスク: 到達可能なベースケースがないと無限再帰とスタックオーバーフローが発生し、深い再帰はメモリを枯渇させ、重複作業にはループやメモ化が必要である。
何が問題でしたか?この内容はサイトの運営チームだけが確認します。