재귀
도입됨
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. |
자신을 포함하는 정의
- 조상(ancestor)이 무엇인지 어떻게 정의할 수 있는가? 당신의 부모는 조상이다. 또한 부모의 조상도 조상이다. 이 두 문장은 무한한 사슬을 정의하며, 두 번째 문서는 그 자체가 정의하는 단어를 사용하고 있다.
- 이는 순환 논리가 아니다. 첫 번째 문장이 사슬이 멈출 수 있는 지점을 제시하기 때문이다. 이것이 없다면 정의는 끝없이 풀려 나가게 된다.
- 프로그램은 같은 방식으로 작성될 수 있으며, 이러한 사슬 형태로 형성된 문제에 대해 재귀적 해법은 루프보다 현저히 짧다.
- 이 수업은 기본 경우(base case) 와 재귀적 경우(recursive case), 재귀 호출이 추적되는 방식, 그리고 아래에서 호출 스택(call stack) 이 무엇을 하는지 다룬다.

두 가지 경우
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
- 기본 경우는 더 이상 호출 없이 직접 답할 수 있을 만큼 작은 문제의 버전이며, 이것이 재귀를 멈춘다.
- 재귀적 경우는 더 작은 입력으로 함수를 다시 호출하여 기본 경우로 나아가게 한다.
- 둘 다 필요하다. 기본 경우가 없는 재귀는 절대 멈추지 않으며, 입력이 shrinking되지 않는 재귀는 기본 경우에 도달하지 못한다.

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.
worked example: 재귀 추적하기
Factorial(4)추적(trace).- 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을 반환한다. - Unwinding:
2 * 1 = 2is returned, then3 * 2 = 6, then4 * 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값을 가진 별개의 호출이기 때문이다. - 이 복사본들은 호출 스택(call stack) 위의 스택 프레임(stack frame) 에 위치한다: 진행 중인 호출마다 하나의 프레임이 있으며, 매개변수, 로컬 변수, 반환 주소를 담고 있다.
- 각 호출 시 프레임이 푸시되고 반환될 때 팝됩니다. 그래서 값들이 호출된 순서와 반대로 돌아옵니다: 호출 스택은 정확히 주제 10의 ADT인 스택입니다.
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.
문제가 발생하는 경우
- 기본 CASE가 없거나 도달할 수 없는 기본 CASE: 재귀가 멈추지 않으며 프레임이 쌓이고 호출 스택의 메모리가 고갈된다. 이를 스택 오버플로우(stack overflow) 라고 한다.
- 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.
- Repeated work: naive recursive Fibonacci recomputes the same values exponentially many times. Fix it with a loop, or with memoisation, storing each result the first time it is computed.

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.
재귀 또는 반복(iteration)
- 재귀는 자기 유사(self-similar) 문제에 적합하다. 즉, 문제가 자체의 더 작은 복사본을 포함하는 경우: 트리 Traverse, 이진 검색 및 병합 정렬과 같은 분할 정복(divide and conquer), 그리고 위 조상 사슬.
- Iteration suits everything else, and uses no extra memory for the repetition.
- 모든 재귀적인 것은 반복적으로 작성할 수 있으며, 그 반대도 true이다. 선택은 스택 비용이라는 메모리와 대비하여 어떤 것이 문제를 명확하게 표현하는지에 관한 것이다.

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.
worked example: 위험을 서술하라
- 학생이 재귀_argv를 작성하여 스택 오버플로로 충돌했습니다. 가능한 원인 두 가지를 제시하십시오.
- 기본 CASE가 없거나, 입력이 각 호출마다 작아지지 않아 기본 CASE에 도달할 수 없어 호출이 계속되고 프레임이 축적된다.
- 재귀는 correct하지만 너무 깊다: 매우 많은 호출 중 각각이 자체의 스택 프레임을 유지하므로, 기본 CASE에 도달하기 전에 호출 스택의 메모리가 고갈된다.
- 두 원인 모두 프레임이 축적되는 것과 관련이 있다. 무엇이 축적되고 왜 멈추지 않는지 말하라.
놓칠 수 있는 점
- A recursion needs both a base case and an input that gets smaller. Naming only the base case is half the condition.
- 추적에서 호출이 확장되는 과정(winding up) 과 값이 축소되는 과정(unwinding) 을 모두 보여야 합니다. 두 방향 모두 점수를 받습니다.
- 각 호출은 자체 스택 프레임 내에서 고유한 매개변수와 로컬 변수를 가집니다. 그래서 재귀는 반복(iteration)이 소모하지 않는 메모리를 소모합니다.
- 스택 오버플로우는 산술 오버플로우가 아니라 프레임이 너무 많아 스택 메모리를 고하는 것이다.
이해했습니다
- 재귀 routine은 기본 CASE를 직접 해결하고, 재귀적 경우에서 더 작은 입력으로 self를 호출해야 한다.
- 두 방향으로 추적하십시오: 기본 사례까지 확장되는 호출, 그리고 다시 축소되어 돌아오는 값들
- 각 호출은 호출 스택(call stack) 위에 자체 스택 프레임을 가지며, 호출 시 푸시되고 반환 시 팝되므로 재귀는 메모리를 소모합니다.
- 리스크: 도달 가능한 기본 사례가 없어 무한 재귀와 스택 오버플로우가 발생하며, 깊은 재귀는 메모리를 소모하고, 반복적인 작업은 루프나 메모이제이션이 필요합니다
어떤 문제가 있었나요? 사이트 팀만 이 내용을 볼 수 있습니다.